简体   繁体   English

C# 正则表达式仅在字符串中找到一组数字时才匹配

[英]C# Regex match only if one group of numbers is found in string

I'm trying to come up with a regex to deal with a general scenario to capture a number from a string where the number may have one or more non-numeric characters pre/post-fixed to it.我正在尝试提出一个正则表达式来处理从字符串中捕获数字的一般情况,其中该数字可能具有一个或多个预先/后固定的非数字字符。
The number can contain zero or one decimal or comma.该数字可以包含零个或一个小数点或逗号。
If the string contains multiple "sets" of consecutive digits separated by non-digits I would like the regex to fail ("sets" is probably not the correct terminology).如果字符串包含多个由非数字分隔的连续数字“集合”,我希望正则表达式失败(“集合”可能不是正确的术语)。

As an example the following inputs would succeed with a match:例如,以下输入将成功匹配:
abc12.00xyz would match 12.00 abc12.00xyz将匹配 12.00
0.1$ would be valid and match 0.1 0.1$将是有效的并且匹配 0.1
.01 would be valid and match .01 .01将有效并匹配 .01
123abc would be valid and match 123 123abc将是有效的并且匹配 123
abc123 would be valid and match 123 abc123将是有效的并且匹配 123

These inputs would fail to match:这些输入将无法匹配:
abc12.00xyz322 would fail due to the second "set" of digits, 322 in this example abc12.00xyz322将由于第二个“组”数字而失败,在本例中为 322
12t2 would fail due to having two separate "sets" of digits 12t2会因为有两个单独的“组”数字而失败

I've tried many permutations and I'm not making much headway.我尝试了很多排列,但没有取得太大进展。 This is the closest I've come to so far.这是迄今为止我最接近的一次。 It matches on the numbers correctly, excluding the non-digits from the match, but it includes all "sets" of numbers in the string.它正确匹配数字,从匹配中排除非数字,但它包括字符串中的所有“集合”数字。

([\\d]*[.,])?[\\d]+

Any suggestions would be appreciated.任何建议,将不胜感激。

You can use a capture group:您可以使用捕获组:

^[^0-9\r\n]*?([0-9]*\.?[0-9]+)[^0-9\r\n]*$
  • ^ Start of string ^字符串开始
  • [^0-9\\r\\n]* Optionally match any char except a digit or a newline, as few as possible [^0-9\\r\\n]*可选匹配除数字或换行符以外的任何字符,尽可能少
  • ([0-9]*\\.?[0-9]+) Capture group 1 , match optional digits, optional comma and 1+ digits ([0-9]*\\.?[0-9]+)捕获组 1 ,匹配可选数字,可选逗号和 1+ 数字
  • [^0-9\\r\\n]* Optionally match any char except a digit or a newline [^0-9\\r\\n]*可选匹配除数字或换行符以外的任何字符
  • $ End of string $字符串结尾

See a .NET regex demo (Click on the Table tab to see the capture group values)查看.NET regex 演示(单击“表”选项卡以查看捕获组值)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM