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

时间:2009-03-18 19:38:59

标签: java regex

我正在尝试找到一种很好的方法来捕获距离给定字符串不超过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个字符。

4 个答案:

答案 0 :(得分:5)

怎么样?
age[^0-9]{0,4}[0-9]+

如果你想捕捉可能找到的号码:

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

答案 1 :(得分:3)

如下所示:

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

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

在这里扩展其他答案,如果你需要在任何一个方向上都在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];
相关问题