regex to find number of specific length, but with any character except a number before or after it

半腔热情 提交于 2019-12-11 10:21:59

问题


I'm trying to work out a regex pattern to search a string for a 12 digit number. The number could have any number of other characters (but not numbers) in front or behind the one I am looking for.

So far I have /([0-9]{12})/ which finds 12 digit numbers correctly, however it also will match on a 13 digit number in the string.

the pattern should match 123456789012 on the following strings

  • "rgergiu123456789012ergewrg"
  • "123456789012"
  • "#123456789012"
  • "ergerg ergerwg erwgewrg \n rgergewrgrewg regewrge 123456789012 ergwerg"

it should match nothing on these strings:

  • "123456789012000"
  • "egjkrgkergr 123123456789012"

回答1:


What you want are look-arounds. Something like:

/(?<![0-9])[0-9]{12}(?![0-9])/

A lookahead or lookbehind matches if the pattern is preceded or followed by another pattern, without consuming that pattern. So this pattern will match 12 digits only if they are not preceded or followed by more digits, without consuming the characters before and after the numbers.




回答2:


/\D(\d{12})\D/ (in which case, the number will be capture index 1)

Edit: Whoops, that one doesn't work, if the number is the entire string. Use the one below instead

Or, with negative look-behind and look-ahead: /(?<!\d)\d{12}(?!\d)/ (where the number will be capture index 0)


if( preg_match("/(?<!\d)\d{12}(?!\d)/", $string, $matches) ) {
    $number = $matches[0];
    # ....
}

where $string is the text you're testing



来源:https://stackoverflow.com/questions/9218950/regex-to-find-number-of-specific-length-but-with-any-character-except-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!