Regex 正则表达式中的字符串--xy

Regex 正则表达式中的字符串--xy,regex,Regex,快速提问。我有这根绳子 string--xy 我设法把常数记下来 /(字符串)(-)(X)(Y)/ 我的问题是xy。X和Y可以在1-999之间,没有前导零,因此无需检查 string -- ([1-9]\d{0,2}) ([1-9]\d{0,2}) string -- matches the characters string -- literally (case sensitive) 1st Capturing group ([1-9]\d{0,2}) [1-9] matc

快速提问。我有这根绳子

string--xy

我设法把常数记下来

/(字符串)(-)(X)(Y)/

我的问题是xy。X和Y可以在1-999之间,没有前导零,因此无需检查

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

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]
示例

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})

对于数字部分,您应该检查
[1-9][0-9]{0,2}
。否则,您将丢失有效数字,例如
10
101

这将与999不匹配。@b是的,会的,请单击Debuggex演示。它将证明它与999Ha匹配抱歉没有看到前导的
[1-9]
10
不是有效数字?你的正则表达式不包含任何零,不仅仅是前导零@karakfa不正确..请使用debuggex演示来显示它是否正确。10 02不起作用的原因是02在一行中…这是一个前导零。也许,有一个更好的标题会有用。类似于“数字字符串中的前导零”或“字符串中的数字范围”是的,同样,我猜老眼睛不会注意到那里的
\d