当前位置:网站首页>正则替换【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:所有的数字- 以
*数字*形式返回
边栏推荐
- Journal des problèmes de brosse à boutons de force / day6 / 6.28
- 其他InterSystems %Net工具
- Interview summary of large factory Daquan II
- How to modify icons in VBS or VBE
- Load test practice of pingcode performance test
- The block:usdd has strong growth momentum
- 提升复杂场景三维重建精度 | 基于PaddleSeg分割无人机遥感影像
- 资料下载 丨首届腾讯技术开放日课程精华!
- LD_ LIBRARY_ Path environment variable setting
- Scala基础教程--20--Akka
猜你喜欢

Wanghongru research group of Institute of genomics, Chinese Academy of Agricultural Sciences is cordially invited to join

Scala基础教程--15--递归

vbs或vbe如何修改图标

Scala basic tutorial -- 18 -- set (2)

被忽视的问题:测试环境配置管理

Nature microbiology | viral genomes in six deep-sea sediments that can infect Archaea asgardii

How is the entered query SQL statement executed?

Scala基础教程--20--Akka

Torchdrug tutorial

力扣刷题日记/day8/7.1
随机推荐
Is it safe to download the mobile version of Anxin securities and open an account online
[system disk back to U disk] record the operation of system disk back to U disk
PB的扩展DLL开发(超级篇)(七)
LD_LIBRARY_PATH 环境变量设置
Scala基础教程--13--函数进阶
Mysql5.7 installation tutorial graphic explanation
Li Kou brush question diary /day5/2022.6.27
力扣刷题日记/day7/6.30
Scala basic tutorial -- 13 -- advanced function
Uni app and uviewui realize the imitation of Xiaomi mall app (with source code)
使用SSH
力扣刷题日记/day5/2022.6.27
SIGMOD’22 HiEngine论文解读
Li Kou brush question diary /day7/2022.6.29
Li Kou brush question diary /day2/2022.6.24
Li Kou brush question diary /day3/2022.6.25
Is it safe to open an account online? is that true?
Halcon template matching
李迟2022年6月工作生活总结
android使用SQLiteOpenHelper闪退