当前位置:网站首页>正则替换【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
:所有的数字- 以
*数字*
形式返回
边栏推荐
- Wireshark抓包TLS协议栏显示版本不一致问题
- How to open an account is safe,
- 6.26CF模拟赛B:数组缩减题解
- . Net ORM framework hisql practice - Chapter 2 - using hisql to realize menu management (add, delete, modify and check)
- 其他InterSystems %Net工具
- Scala基础教程--18--集合(二)
- 【机器学习的数学基础】(一)线性代数(Linear Algebra)(上+)
- 技术分享 | 接口测试价值与体系
- Scala基础教程--17--集合
- ESP32-C3入门教程 问题篇⑫——undefined reference to rom_temp_to_power, in function phy_get_romfunc_addr
猜你喜欢
基于NCF的多模块协同实例
被忽视的问题:测试环境配置管理
Li Kou brush question diary /day7/2022.6.29
Mxnet implementation of googlenet (parallel connection network)
[mathematical modeling of graduate students in Jiangxi Province in 2022] analysis and code implementation of haze removal by nucleation of water vapor supersaturation
Scala basic tutorial -- 17 -- Collection
基于lex和yacc的词法分析器+语法分析器
Scala基础教程--20--Akka
Wireshark packet capturing TLS protocol bar displays version inconsistency
一种将Tree-LSTM的强化学习用于连接顺序选择的方法
随机推荐
Lua EmmyLua 注解详解
Esp32-c3 introductory tutorial questions ⑫ - undefined reference to ROM_ temp_ to_ power, in function phy_ get_ romfunc_ addr
Scala基础教程--12--读写数据
提升复杂场景三维重建精度 | 基于PaddleSeg分割无人机遥感影像
[cloud voice suggestion collection] cloud store renewal and upgrading: provide effective suggestions, win a large number of code beans, Huawei AI speaker 2!
Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology
fopen、fread、fwrite、fseek 的文件处理示例
如何提高开发质量
The block:usdd has strong growth momentum
Torchdrug tutorial
力扣刷题日记/day8/7.1
资料下载 丨首届腾讯技术开放日课程精华!
6.26CF模拟赛B:数组缩减题解
力扣刷题日记/day6/6.28
Li Kou brush question diary /day4/6.26
I always thought that excel and PPT could only be used for making statements until I saw this set of templates (attached)
Scala基础教程--13--函数进阶
Crawler (6) - Web page data parsing (2) | the use of beautifulsoup4 in Crawlers
Nature Microbiology | 可感染阿斯加德古菌的六种深海沉积物中的病毒基因组
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