我正试图想出一个快速解决方案来查找字符串中的部分。这是一个示例字符串:
“PostLoad成功!您将 17.00 Rs的金额转移到 03334224222 。现在通过拨打123使用PostLoad。短信上的PostLoad将于01-03-2011结束。”
目标:需要检索粗体值:金额和单元格编号。字符串内容略有变化,但单元格数字始终为11位数。金额始终为两位小数精度。任何使用C#和RegEx的建议?
答案 0 :(得分: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
}
}
<强>解释强>
( # 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
组#1将包含十进制数字,组#2将包含11位数字。
“单词边界”是字母数字字符和非字母数字字符之间的位置,因此它仅匹配“单词或数字”的开头或结尾。
这可确保12.3456
之类的数字不会匹配;另一方面,数字必须用空格,标点符号或其他非alnum字符分隔。例如,在number12.34
中,正则表达式与12.34
不匹配。
答案 1 :(得分:0)
这是对VB.Net的转换。我希望我做对了。
Dim regexObj As New Regex("(\b\d+\.\d{2}\b).*?(\b\d{11}\b)")
Dim matchResults As Match = regexObj.Match(lActualSenderMessage)
While matchResults.Success
For i As Integer = 1 To matchResults.Groups.Count - 1
Dim groupObj As Group = matchResults.Groups(i)
' matched text: groupObj.Value
' match start: groupObj.Index
' match length: groupObj.Length
If groupObj.Success Then
End If
Next
End While