我正试图想出一个快速的解决方案来查找字符串中的部分.这是一个Sample字符串:
"PostLoad成功!您将17.00卢比的金额转移到03334224222.现在通过拨打123使用PostLoad.短信的PostLoad将于01-03-2011结束."
目标:需要检索粗体值:金额和单元格编号.字符串内容略有变化,但单元格数字始终为11位数.金额始终为两位小数精度.使用C#和RegEx的任何建议?
Tim*_*ker 10
Regex regexObj = new Regex(@"(\b\d+\.\d{2}\b).*?(\b\d{11}\b)");
Match matchResults = regexObj.Match(subjectString);
while (matchResults.Success) {
for (int i = 1; i < matchResults.Groups.Count; i++) {
Group groupObj = matchResults.Groups[i];
if (groupObj.Success) {
// matched text: groupObj.Value
// match start: groupObj.Index
// match length: groupObj.Length
}
}
Run Code Online (Sandbox Code Playgroud)
说明:
( # Match and capture the following:
\b # Assert that the match starts at a "word boundary"
\d+ # Match one or more digits
\. # Match a .
\d{2} # Match exactly two digits
\b # Assert that the number ends here
) # End of first capturing group
.*? # Match any number of intervening characters; as few as possible
( # Match and capture...
\b # Word boundary
\d{11} # Exactly 11 digits
\b # Word boundary
) # End of match
Run Code Online (Sandbox Code Playgroud)
组#1将包含十进制数,组#2将包含11位数.
"单词边界"是字母数字字符和非字母数字字符之间的位置,因此它仅匹配"单词或数字"的开头或结尾.
这可以确保数字12.3456不匹配; 另一方面,数字必须用空格,标点符号或其他非alnum字符分隔.例如,在number12.34正则表达式中不匹配12.34.