简体   繁体   中英

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.

For example, if the String is "age" and N=4 have to find

"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".

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"

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

and then get the contents of the first group ($1).

Expanding on the other answers here, if you need it to be within 5 characters in either direction:

/((\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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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