您的位置 首页 java

正则表达式分组与引用实战

目录

分组与编号

分组引用

不保存子组

分组引用在查找中使用

分组引用在替换中使用

总结


括号在正则中的功能就是用于分组。简单来理解 就是,由多个元字符组成某个部分,应该被看成一个整体的时候,可以用括号括起来表示一 个整体,这是括号的一个重要功能。其实用括号括起来还有另外一个作用,那就是“复用”。

分组与编号

括号在正则中可以用于分组,被括号括起来的部分“子表达式”会被保存成一个子组。

正则表达式分组与引用实战

正则表达式分组与引用实战

分组引用

正则表达式分组与引用实战

正则表达式分组与引用实战

不保存子组

  • 如果正则中出现了括号,那么我们就认为,这个子表达式在后续可能会再次被引用,所以不保存子组可以提高正则的性能。
  • 这么做还有一些好处,由于子组变少了,正则性能会更好,在子组计数时也更不容易出错。

正则表达式分组与引用实战

正则表达式分组与引用实战

分组引用在查找中使用

需求:要 找重复出现2次的单词

用 w+ 来表示一个单词

正则表达式分组与引用实战

正则表达式分组与引用实战

如果某个单词出现三次呢?

the little cat cat is in the hat hat hat, we like it.

要变成:

the little cat is in the hat, we like it.

解决: 1 此时无法满足需求,应该对其进行改造。在引用前加上一个空格。进行匹配

就变成了 空格+引用 出现1或者多次

 /
(w+)(s1)+
/
gm
1st Capturing Group (w+)
w matches any word character (equivalent to [a-zA-Z0-9_])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
2nd Capturing Group (s1)+
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data
s matches any whitespace character (equivalent to [rntfv ])
1 matches the same text as most recently matched by the 1st capturing group
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)  

正则表达式分组与引用实战

正则表达式分组与引用实战

正则表达式分组与引用实战

没有考虑到的地方: 如果手抖多敲一个空格就GG了。

所以应该 这样写: (bw+)(s+1)+

分组引用在替换中使用

需求:日期的转换

2022-02-17 转换为2022 年 02 月 17 日

日期分组编号是 1,时间分组编号是 5,年月日对应的分组编号分别是 2,3,4,时分秒的

分组编号分别是 6,7,8。

正则表达式分组与引用实战

正则表达式分组与引用实战

 ((d{4})-(d{2})-(d{2})) ((d{2}):(d{2}):(d{2}))

2022-02-17 15:30:36  

正则表达式分组与引用实战

点进去试试!

regex101: build, test, and debug regex

正则表达式分组与引用实战

正则表达式分组与引用实战

总结​​

​​

文章来源:智云一二三科技

文章标题:正则表达式分组与引用实战

文章地址:https://www.zhihuclub.com/180009.shtml

关于作者: 智云科技

热门文章

网站地图