当前位置:网站首页>正则替换【JS,正则表达式】
正则替换【JS,正则表达式】
2022-07-04 17:16:00 【qq_22841387】
问题描述
表示数字_牛客题霸_牛客网 (nowcoder.com)
题目要求将所有的数字替换成*数字*
原本这道题我准备就常规使用c++去写的,但是写的过程中突然意识到
所有数字替换,不就是找到所有数字后替换吗?那不就可以使用正则表达式
了
带着这个想法,我去寻找对应的正则表达式
解决代码
var value = readline();
console.log(value.replace(/(\d+)/g, (number) => {
return `*${
number}*`;
} ))
没错,就两句话……提交答案成功的那一刻我也有一点点震惊……
思路历程
其实开始我拿到这个题目的时候,我当时已经知道了通过正则可以替换了,但是就是差那么一个点,让我能解决这道题如何不只是替换,而是加上字符后替换
于是发现可以使用函数去替换
1.获取到所有数字
首先第一步就是通过正则表达式获取到所有的数字,/(\d+)/g
(\d+)
:匹配一个或多个数字/g
:全局匹配,与replaceAll类似
其实我知道如何去替换数字
/[0-9]/g
,也同样可以匹配到所有的数字,但是却不是我们想要的结果。
通过/[0-9]/g
去寻找数字,只能找到一个数字,因为只有一个数字是满足0-9这个条件的
而通过(\d+)
则可以匹配到连续的多个数字
2.替换赋值
找到所有数字之后,第二步就是如何去将数字替换成*数字*
了。
直接通过函数去处理
(number) => {
return `*${
number}*`;
}
因为第一步,我们已经找出了所有的连续的数字,那么我们就可以将这些找到的数字接起来,处理之后,再返回出去
number
:所有的数字- 以
*数字*
形式返回
边栏推荐
- 【机器学习的数学基础】(一)线性代数(Linear Algebra)(上+)
- 谷粒商城(一)
- Scala基础教程--13--函数进阶
- [2022 Jiangxi graduate mathematical modeling] curling movement idea analysis and code implementation
- .NET ORM框架HiSql实战-第二章-使用Hisql实现菜单管理(增删改查)
- Reptile elementary learning
- Imitation of numpy 2
- What types of Thawte wildcard SSL certificates provide
- [go ~ 0 to 1] read, write and create files on the sixth day
- 如何使用 wget 和 curl 下载文件
猜你喜欢
力扣刷题日记/day4/6.26
Scala基础教程--19--Actor
I always thought that excel and PPT could only be used for making statements until I saw this set of templates (attached)
能源行业的数字化“新”运维
[mathematical modeling of graduate students in Jiangxi Province in 2022] analysis and code implementation of haze removal by nucleation of water vapor supersaturation
[HCIA continuous update] network management and operation and maintenance
Improve the accuracy of 3D reconstruction of complex scenes | segmentation of UAV Remote Sensing Images Based on paddleseg
Torchdrug tutorial
An example of multi module collaboration based on NCF
中国农科院基因组所汪鸿儒课题组诚邀加入
随机推荐
What types of Thawte wildcard SSL certificates provide
[go ~ 0 to 1] read, write and create files on the sixth day
【系统盘转回U盘】记录系统盘转回U盘的操作
MySQL common add, delete, modify and query operations (crud)
Journal des problèmes de brosse à boutons de force / day6 / 6.28
6.26CF模拟赛E:价格最大化题解
Interview summary of large factory Daquan II
Just today, four experts from HSBC gathered to discuss the problems of bank core system transformation, migration and reconstruction
Digital "new" operation and maintenance of energy industry
输入的查询SQL语句,是如何执行的?
Scala基础教程--20--Akka
NBA赛事直播超清画质背后:阿里云视频云「窄带高清2.0」技术深度解读
2022 ByteDance daily practice experience (Tiktok)
发送和接收IBM WebSphere MQ消息
Scala basic tutorial -- 18 -- set (2)
ThreadLocal原理与使用
【OpenCV入门到精通之九】OpenCV之视频截取、图片与视频互转
线上MySQL的自增id用尽怎么办?
LD_ LIBRARY_ Path environment variable setting
一、C语言入门基础