简体   繁体   English

为什么此RegExp无法正常工作?

[英]Why doesn't this RegExp work as expected?

I made a RegExp to format an incoming date string, but it doesn't work as expected with my usage. 我做了一个RegExp来格式化传入的日期字符串,但是它不能按预期使用。 I was hoping someone could explain why not: 我希望有人可以解释为什么不这样:

 var data = [ "m_2013_01_01", "m_2013_02_01", "m_2013_03_01", "m_2013_04_01" ]; // why aren't these equivalent? // expected console.log(data.map(datum => datum.replace(/^m_(\\d+)_(\\d+)_(\\d+)/g, '$1-$2-$3'))); // ??? console.log(data.map(datum => datum.replace(/^m_(?:(\\d+)_?){3}$/g, '$1-$2-$3'))); 

In the fist regex you are using 3 groups: 在第一个正则表达式中,您使用3组:

正则表达式可视化

That's why you can reference group 1, 2 and 3. 这就是为什么您可以引用组1、2和3。

However, in the second regex you are using 1 group repeated multiple time, so group 2 and 3 doesn't exist and can't be referenced: 但是,在第二个正则表达式中,您使用的是重复多次的1组,因此组2和3不存在并且无法被引用:

正则表达式可视化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM