[英]RegEx for capturing numbers in parentheses
例
Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]
我想獲得15.7
的Alarm Level 1
和-12.7
從Alarm Level 2
。 我嘗試使用\\((.*?)\\)
但15.7 in Alarm Level 1
得到了D1
和15.7 in Alarm Level 1
。
解決此問題的最簡單方法可能是匹配以下模式:
\[[^(]+\((-?\d+(?:\.\d+)?)\)\]
這里的策略是匹配整個術語,例如[High (-12.7)]
,然后在圓括號內捕獲數字。
例如,在Python中,我們可以嘗試以下操作:
input = """Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]"""
matches = re.findall(r'\[[^(]+\((-?\d+(?:\.\d+)?)\)\]', input)
print(matches)
打印:
['15.7', '-12.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}`); }); }
jex.im可視化正則表達式:
使用正則表達式,其模式為:
\[\w+\s\\([\d.-]+\\)\]
通過匹配來匹配“ [低(15.7)]”或“ [高(-12.7)]”
一種。 “ [”&“]”匹配方括號
灣 “ \\ w +”以匹配一個或多個單詞(在這種情況下為“低”或“高”)
C。 “ \\ s”以匹配單個空格
d。 “ \\(”&“ \\)”以匹配括號
即 [\\ d .-] +匹配數字的組合“。” &“-”
依次為:
[\d.-]+
捕捉所需的價值
源代碼:
static void Main(string[] args)
{
string input = "Alarm Level 1 (D1) [Low (-15.7)]";
string pattern = @"\[\w+\s\([\d.-]+\)\]";
string outputA = Regex.Match(input, pattern).Value;
string outputB = Regex.Match(outputA, @"[\d.-]+").Value;
Console.WriteLine("A: " + outputA);
Console.WriteLine("B: " + outputB);
Double intOutput = Convert.ToDouble(outputB);
Console.ReadLine();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.