gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:45:27 25 4
gpt4 key购买 nike

示例

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com