我们将使用下面的正则表达式来获取单词之前的数字。
范例:
838123 someWord 8 someWord 12 someWord
(\d+)\s*someWord
但是有时数字和单词之间会出现任何东西。请参见下面的示例行。
例如:
someword 12的43434 someword 2323 new someword
如何使用正则表达式获取该单词之前的确切数字?
请给我您的建议。
我们将使用下面的正则表达式来获取单词之前的数字。
范例:
838123 someWord 8 someWord 12 someWord
(\d+)\s*someWord
但是有时数字和单词之间会出现任何东西。请参见下面的示例行。
例如:
someword 12的43434 someword 2323 new someword
如何使用正则表达式获取该单词之前的确切数字?
请给我您的建议。
Answers:
您可以尝试这样的事情:
(\d+)\s?([^\d]*)
(\d+) - get the digits
\s? - discard a possible space
([^\d]*) - get all chars that are not digits
你可以在这里看到测试
第一分离的some[wW]ord
,number
和space
带有图案,然后执行在其上的第二图案
var pattern = @"\b(some[wW]ord|[\d]|\s)*\b";
var rgx = new Regex(pattern);
var sentence = "43434 of someword 12 anything someword 2323 new someword";
var result = string.Empty;
foreach (Match match in rgx.Matches(sentence)){
result += match.Value;
}
//output => result: 43434 someword 12 someword 2323 someword
var patternOnCorrectSentence = @"\b(\d+)\s*some[wW]ord*\b";
var rgxOnCorrectSentence = new Regex(patternOnCorrectSentence);
var resultOnCorrectSentence = new List<string>();
foreach (Match match in rgxOnCorrectSentence.Matches(result)){
resultOnCorrectSentence.Add(match.Value);
}
resultOnCorrectSentence.ForEach(Console.WriteLine);
Console.ReadKey();
当执行第一个模式时,该句子将是所需的
someword 12的43434 someword 2323 new someword
更改:
43434某个单词12某个单词2323某个单词
使用命名匹配捕获(要获取数据,请使用mtch.Groups["Value"].Value
...等)以根据需要提取信息。
(?<Value>\d+) -- Get the digits
(?<Other>.+?) -- Capture all text, but minimal (greedy) capture
(?<Key>someword) -- til the keyword here.
当上述运行(与IgnorePatternWhiteSpace
以其它方式去除的评论和加入模式运行它如(?<Value>\d+)(?<Other>.+?)(?<Key>someword)
不带正则表达式的选项)它获取的数据对每个数据/密钥对,并组织在每个单个的匹配。
结果
这是结果(对于第二个示例),所有结果都包含在单个匹配项中,并且每个匹配项中都包含它们的组和捕获:
Match #0
[0]: 43434˽of˽someword
["Value"] → [1]: 43434
→1 Captures: 43434
["Other"] → [2]: ˽of˽
→2 Captures: ˽of˽
["Key"] → [3]: someword
→3 Captures: someword
Match #1
[0]: 12˽anything˽someword
["Value"] → [1]: 12
→1 Captures: 12
["Other"] → [2]: ˽anything˽
→2 Captures: ˽anything˽
["Key"] → [3]: someword
→3 Captures: someword
Match #2
[0]: 2323˽new˽someword
["Value"] → [1]: 2323
→1 Captures: 2323
["Other"] → [2]: ˽new˽
→2 Captures: ˽new˽
["Key"] → [3]: someword
→3 Captures: someword
视觉上这是匹配的内容: