当前位置:网站首页>正则替换【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:所有的数字- 以
*数字*形式返回
边栏推荐
- 被忽视的问题:测试环境配置管理
- Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology
- Scala basic tutorial -- 12 -- Reading and writing data
- [go ~ 0 to 1] read, write and create files on the sixth day
- How is the entered query SQL statement executed?
- 基于unity的愤怒的小鸟设计
- How is the entered query SQL statement executed?
- How to download files using WGet and curl
- Scala基础教程--13--函数进阶
- 力扣刷题日记/day7/2022.6.29
猜你喜欢

An example of multi module collaboration based on NCF

vbs或vbe如何修改图标

ByteDance dev better technology salon was successfully held, and we joined hands with Huatai to share our experience in improving the efficiency of web research and development

How is the entered query SQL statement executed?

Unity 制作旋转门 推拉门 柜门 抽屉 点击自动开门效果 开关门自动播放音效 (附带编辑器扩展代码)

基于lex和yacc的词法分析器+语法分析器

Journal des problèmes de brosse à boutons de force / day6 / 6.28

How to improve development quality

机器学习概念漂移检测方法(Aporia)

Scala basic tutorial -- 20 -- akka
随机推荐
Microservice architecture debate between radical technologists vs Project conservatives
Blue bridge: sympodial plant
PB的扩展DLL开发(超级篇)(七)
网上开户安全吗?是真的吗?
Grain Mall (I)
Reptile elementary learning
能源行业的数字化“新”运维
C language printing exercise
Mxnet implementation of googlenet (parallel connection network)
Principle and application of ThreadLocal
Wireshark packet capturing TLS protocol bar displays version inconsistency
Crawler (6) - Web page data parsing (2) | the use of beautifulsoup4 in Crawlers
Pb extended DLL development (super chapter) (VII)
Scala基础教程--17--集合
Scala basic tutorial -- 19 -- actor
TCP waves twice, have you seen it? What about four handshakes?
SIGMOD’22 HiEngine论文解读
How to improve development quality
字节跳动Dev Better技术沙龙成功举办,携手华泰分享Web研发效能提升经验
力扣刷题日记/day1/2022.6.23