我正在尝试创建一个正则表达式来从字符串中提取数据。我的示例字符串:dn1:pts-sc1.1
。我期望的数据格式:['pts', 'sc', '1.1']
所以基本上 之后的每一组字母:
和末尾的数字。
我是什么 have right now :
/^[^:]+:(?:([a-z]+)-?)+([\d\.]+)$/g
不幸的是,它只返回最后一组字母。
['sc', '1.1']
我还尝试将 +
添加到第一个捕获组:
/^[^:]+:(?:([a-z]+)+-?)+([\d\.]+)$/g
结果是一样的。唯一不同的是 regex101 给了我这个评论:
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
--编辑
输入字符串的例子:
dn2.33:sc-pts-tt-as3.43
dn2.33:sc3.43
dn2.33:sc-tt-as3.43
所以基本上我不知道字母组的数量。
最佳答案
您可能无法获得任意数量的组,它们的数量由您的模式中捕获组的数量指定。您可以将 -
分隔的值匹配并捕获到一组中,然后用 -
将其拆分以获取单个项目并动态构建结果:
var strs = ['dn2.33:sc-pts-tt-as3.43','dn2.33:sc3.43','dn2.33:sc-tt-as3.43'];
var rx = /^[^:]+:([a-z]+(?:-[a-z]+)*)([\d.]+)$/; // Define the regex
for (var s of strs) {
var res = []; // The resulting array variable
var m = rx.exec(s); // Run the regex search
if (m) { // If there is a match...
res = m[1].split('-'); // Split Group 1 value with - and assign to res
res.push(m[2]); // Add Group 2 value to the resulting array
}
console.log(s, "=>", res);
}
模式 - ^[^:]+:([a-z]+(?:-[a-z]+)*)([\d.]+)$
- 将匹配以下内容:
^
- 字符串的开始[^:]+
- 除了:
之外的 1+ 个字符
:
- 冒号([a-z]+(?:-[a-z]+)*)
- 第 1 组(它将是abc-def-ghij
...): 1 个或多个字母后跟 0+ 个连续的-
序列和 1+ 个字母(添加/i
修饰符以使模式不区分大小写)([\d.]+)
- 第 2 组(它可以作为m[2]
被“插入”结果数组):1或更多数字或.
$
- 字符串结尾。
关于javascript - JS Regex 多个捕获组返回所有匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47433771/