简体   繁体   中英

Quick PHP regex for digit format

I just spent hours figuring out how to write a regular expression in PHP that I need to only allow the following format of a string to pass:

(any digit)_(any digit)

which would look like:

219211_2

so far I tried a lot of combinations, I think this one was the closest to the solution:

/(\\d+)(_)(\\d+)/

also if there was a way to limit the range of the last number (the one after the underline) to a certain amount of digits (ex. maximal 12 digits), that would be nice.

I am still learning regular expressions, so any help is greatly appreciated, thanks.

You don't need double escaping \\\\d in PHP.

Use this regex:

"/^(\d+)_(\d{1,12})$/"
  • \\d{1,12} will match 1 to 12 digist
  • Better to use line start/end anchors to avoid matching unexpected input

The following:

\d+_\d{1,12}(?!\d)

Will match "anywhere in the string". If you need to have it either "at the start", "at the end" or "this is the whole thing", then you will want to modify it with anchors

^\d+_\d{1,12}(?!d)      - must be at the start
\d+_\d{1,12}$           - must be at the end
^\d+_\d{1,12}$          - must be the entire string

demo: http://regex101.com/r/jG0eZ7

Explanation:

\d+      - at least one digit
_        - literal underscore
\d{1,12} - between 1 and 12 digits
(?!\d)   - followed by "something that is not a digit" (negative lookahead)

The last thing is important otherwise it will match the first 12 and ignore the 13th. If your number happens to be at the end of the string and you used the form I originally had [^\\d] it would fail to match in that specific case.

Thanks to @sln for pointing that out.

Try this:

$regex= '~^/(\d+)_(\d+)$~';
$input= '219211_2';
if (preg_match($regex, $input, $result)) {
 print_r($result);
}

只需尝试以下正则表达式即可:

^(\d+)_(\d{1,12})$

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