繁体   English   中英

正则表达式:查找给定字符串附近的数字

[英]Regular Expression : find a number near to a given String

我正在尝试找到一种好方法来捕获距给定字符串不超过 N 个字符的数字。

例如,如果字符串是“年龄”并且 N=4 必须找到

"Age 5" => 5
"My age is 10 and I my name is John" => 10
"My age is almost 5 and I my name is Mary" => null

在最后一种情况下,数字与“年龄”分开超过 4 个字符。

关于什么

age[^0-9]{0,4}[0-9]+

如果您想捕获可能找到的数字:

age[^0-9]{0,4}([0-9]+)

?

类似于以下内容:

age[^\d]{,4}(\d+)

这意味着“年龄后跟 0 到 4 个非数字后跟一个或多个数字......捕获数字”

[Aa]ge[\D]{,N}(\d+)

然后获取第一组的内容($1)。

在这里扩展其他答案,如果您需要它在任一方向的 5 个字符内:

/((\d+)\D{,4})?age(\D{,4}(\d+))?/i

然后:

if(matches[2] != null)
{
  if(matches[4] != null)
    return max(matches[2], matches[4]);  //or however you want to resolve this..
  else
    return matches[2];
}
return matches[4];

暂无
暂无

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

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