[英]Regular Expression : find a number near to a given String
I am trying to find a good way to capture a number that is at no more than N characters away from a given string.我正在尝试找到一种好方法来捕获距给定字符串不超过 N 个字符的数字。
For example, if the String is "age" and N=4 have to find例如,如果字符串是“年龄”并且 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
In the last case, the number is separated more than 4 characters from "age".在最后一种情况下,数字与“年龄”分开超过 4 个字符。
What about关于什么
age[^0-9]{0,4}[0-9]+
if you want to capture the number possibly found:如果您想捕获可能找到的数字:
age[^0-9]{0,4}([0-9]+)
? ?
Something like the following:类似于以下内容:
age[^\d]{,4}(\d+)
this means "age followed by 0 to 4 non-digits followed by one or more digits...capture the digits"这意味着“年龄后跟 0 到 4 个非数字后跟一个或多个数字......捕获数字”
[Aa]ge[\D]{,N}(\d+)
and then get the contents of the first group ($1).然后获取第一组的内容($1)。
Expanding on the other answers here, if you need it to be within 5 characters in either direction:在这里扩展其他答案,如果您需要它在任一方向的 5 个字符内:
/((\d+)\D{,4})?age(\D{,4}(\d+))?/i
Then:然后:
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.