c# - 用于捕获括号中数字的正则表达式

标签 c# regex

示例

Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]

我想从警报级别1获得15.7,从警报级别2获得-12.7。我尝试使用 \((.*?)\) 但它在警报级别 1 中同时获得 D115.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可视化正则表达式:

enter image description here

关于c# - 用于捕获括号中数字的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56371496/

相关文章:

C#设置默认参数,字符串数组(string[])

regex - sed 尝试在搜索和替换中使用捕获组时前面的正则表达式无效

python - 删除两个句号之间的数字

regex - 为什么在使用正则表达式时 grep 会返回不同的结果?

c# - C# 命名空间中的类、方法

c# - 与 System.Windows.Forms.Timer 的间隔不一致

c# - StringBuilder 和字节转换

C# 相当于 Form.Activate 事件?

JavaScript:使用正则表达式在 Char 和 Number 之间添加空格

c# - 将 c# 正则表达式转换为 javascript 正则表达式