简体   繁体   中英

string — x y in REGEX

Quick question. I have this string

string -- xy

I manage to get the constants down

/(string) (--) (X) (Y)/

my problem is x y. X and Y can be between 1-999 there's no leading zeros so no need to check on that.

string -- ([1-9]\d{0,2}) ([1-9]\d{0,2})

正则表达式可视化

Debuggex Demo

Description

string --  matches the characters string --  literally (case sensitive)
1st Capturing group ([1-9]\d{0,2})
    [1-9] match a single character present in the list below
        1-9 a single character in the range between 1 and 9
    \d{0,2} match a digit [0-9]
        Quantifier: {0,2} Between 0 and 2 times, as many times as possible, giving back as needed [greedy]
      matches the character   literally
2nd Capturing group ([1-9]\d{0,2})
    [1-9] match a single character present in the list below
        1-9 a single character in the range between 1 and 9
    \d{0,2} match a digit [0-9]
        Quantifier: {0,2} Between 0 and 2 times, as many times as possible, giving back as needed [greedy]

Examples

string -- 1 999 //matches
string -- 10 02 //does not match
string -- 011 222 //does not match
string -- 111 222 //matches
string -- 41 2 //matches
string -- 999 1 //matches
string -- 1 1 //matches

您可以使用否定的前瞻表示避免前导零(和零):

/(string) (--)(?!.* 0) (\d{1,3}) (\d{1,3})

For the number portion you should be checking [1-9][0-9]{0,2} . Otherwise you'll miss valid numbers such as 10 and 101 .

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