简体   繁体   English

正则表达式对字符串中的递归模式进行分组并将捕获组作为数组返回

[英]Regex to group recursive pattern in string and return capture group as array

I have a string that looks like this: Hello:A1,A3,A4,AA04我有一个看起来像这样的字符串: Hello:A1,A3,A4,AA04

Right now I have a regex query that looks like this:现在我有一个看起来像这样的正则表达式查询:

/(?<g1>[A-Za-z]+):(?<g2>[A-Za-z0-9,]+)/

When a match is found I can access it like this:找到匹配项后,我可以像这样访问它:

"Hello:A1,A3,A4,AA04".match(/(?<g1>[A-Za-z]+):(?<g2>[A-Za-z0-9,]+)/).groups.g1 // outputs: Hello

ok...now I also have g2 .好的...现在我也有g2 I need g2 in an array with the , gone.我需要一个数组中的g2,消失了。 Right now in my code I have done it this way:现在在我的代码中,我已经这样做了:

"Hello:A1,A3,A4,AA04".match(/(?<g1>[A-Za-z]+):(?<g2>[A-Za-z0-9,]+)/).groups.g2.split(',') // outputs: [ 'A1', 'A3', 'A4', 'AA04' ]

Now the question is: Is it possible to accomplish this without .split(',') by using Regex and have it return like this:现在的问题是:是否可以在没有.split(',')的情况下通过使用 Regex 来完成此操作并使其返回如下:

"Hello:A1,A3,A4,AA04".match(?).groups.g2 // would output: [ 'A1', 'A3', 'A4', 'AA04' ]

I know I'm not the best at explaining this but I tried to find an answer, I'm either missing it or it's not possible.我知道我不是最擅长解释这一点,但我试图找到答案,我要么错过它,要么不可能。 This is not critical or super important just something on my mind.这不是关键或超级重要的,只是我的想法。 Sorry for the horrible title.对不起这个可怕的标题。

running Node.js v13.2.0运行 Node.js v13.2.0

Added a ^ to match beginning of string only.添加了 ^ 以仅匹配字符串的开头。 Using lookaheads.使用前瞻。
Note that lookaheads doesn't have good browser support.请注意,前瞻没有很好的浏览器支持。
Also, I don't know/haven't tested the performance characteristics of this versus exec looping.另外,我不知道/没有测试过这个与 exec 循环的性能特征。 And to be entirely honest, it's not much cleaner looking than split.老实说,它看起来并不比拆分更干净。 If you want a one-liner, this'll suffice I guess.如果你想要一个单线,我想这就足够了。
I remember for very long strings on other platforms using RegExs like this didn't do well.我记得在其他使用 RegEx 的平台上很长的字符串表现不佳。 But I ended up resorting to other methods to searching anyways.但我最终还是求助于其他方法进行搜索。

 console.log( "Hello:A1,A3,A4,AA04".match(/(^[A-Za-z]+(?=:))|((?=,?)([A-Za-z0-9]+))/g) )

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

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