简体   繁体   中英

How to match single digit in a string using regular expression

I have a string:

AB_INV_23_some_value

I want to check the number after AB_INV_ . Condition is that the number should not be more than 4 (and it should be a single digit number).

I wrote a pattern:

^(AB)_(INV)_[0-4]{1}

However, this pattern is a matches AB_INV_23_some_value , while it shouldn't, because 23 is 2-digit number that is more than 4. Please assist.

In your pattern, [0-4]{1} matches exactly 1 digit from 0 to 4 , but it does not check what comes after that digit. There may be anything, even the end of string, or another digit.

You may use

^AB_INV_[0-4](?!\d)

See the regex demo

Details

  • ^ - start of string
  • AB_INV_ - a literal substring
  • [0-4] - a digit from 0 ot 4 ...
  • (?!\\d) - that is not followed by any other digit.

you can do it with the regex

AB_INV_(?![5-9]_)\d{1,4}_

see the regex demo

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