示例
Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]
我想从警报级别1
获得15.7
,从警报级别2
获得-12.7
。我尝试使用 \((.*?)\)
但它在警报级别 1 中同时获得 D1
和 15.7
。
最佳答案
在这里,我们可以尝试使用简单的捕获组来收集数字:
\(([0-9-.]+)\)
测试
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\(([0-9\-\.]+)\)";
string input = @"Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
const regex = /\(([0-9-.]+)\)/gm;
const str = `Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
DEMO
正则表达式电路
jex.im可视化正则表达式:
关于c# - 用于捕获括号中数字的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56371496/