当前位置:网站首页>正则替换【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:所有的数字- 以
*数字*形式返回
边栏推荐
- How to modify icons in VBS or VBE
- [go language question brushing chapter] go conclusion chapter | introduction to functions, structures, interfaces, and errors
- Numpy 的仿制 2
- Principle and application of ThreadLocal
- 完善的js事件委托
- MySQL常用增删改查操作(CRUD)
- Scala基础教程--16--泛型
- 【系统盘转回U盘】记录系统盘转回U盘的操作
- IBM WebSphere MQ检索邮件
- Neglected problem: test environment configuration management
猜你喜欢

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

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

Scala基础教程--16--泛型

【uniapp】uniapp开发app在线预览pdf文件

Grain Mall (I)

Li Kou brush question diary /day7/2022.6.29

Scala basic tutorial -- 20 -- akka

Thawte通配符SSL证书提供的类型有哪些

Wireshark抓包TLS协议栏显示版本不一致问题

Halcon模板匹配
随机推荐
How is the entered query SQL statement executed?
Wireshark抓包TLS协议栏显示版本不一致问题
【系统盘转回U盘】记录系统盘转回U盘的操作
Scala基础教程--13--函数进阶
Interview summary of large factory Daquan II
力扣刷題日記/day6/6.28
2022年字节跳动日常实习面经(抖音)
Scala基础教程--16--泛型
MySQL common add, delete, modify and query operations (crud)
资料下载 丨首届腾讯技术开放日课程精华!
Li Chi's work and life summary in June 2022
[2022 Jiangxi graduate mathematical modeling] curling movement idea analysis and code implementation
6.26cf simulation race e: solution to the problem of price maximization
TCP waves twice, have you seen it? What about four handshakes?
Is it safe to open an account online? is that true?
Pb extended DLL development (super chapter) (VII)
Torchdrug tutorial
Scala基础教程--17--集合
线上MySQL的自增id用尽怎么办?
提升复杂场景三维重建精度 | 基于PaddleSeg分割无人机遥感影像