简体   繁体   中英

regex find one or two digits but not three digits in a string

I would like to find the match for:
\\024jack3hall 2 \\c$
\\024jack3hall 02 \\c$
\\024jack3hall 12 \\c$

but not for:
\\024jack3hall 023 \\c$

difference is the number of digits in the end part. I would like to have only 1 or 2, not 3.
my try:

 \\\\024[a-zA-Z0-9]+[0-9]{1,2}\\[a-zA-Z]{1}\$(?!.)

I tried only on http://regexr.com/ but will implement in C#.
Is it possible to edit my try or I have to write several separate checks? Why is

 {1,2}

not working? \\024jack3hall 12343 \\c$ is also matching,

From the examples you have shown , something as simple as:

[^\d](\d{1,2})\\

Should work. It will match 1 or 2 digits followed by a \\ so long as it isn't proceeded by another digit. The matched digits are in a capture group if you need them (or you can just remove the brackets if you don't need that).

As for your original effort, right here:

\\\\024[a-zA-Z0-9]+[0-9]{1,2}

You are matching 1 or more from the range az , AZ or 0-9 . So that will match your extra digits if they come at the end of that pattern.

回答:

\\\\024[a-zA-Z0-9]+[^\d](\d{1,2})\\[a-zA-Z]{1}\$(?!.)

I believe you were not escaping backslash properly. Here is the correct regex:

\\024[a-zA-Z0-9]+[0-9]{1,2}\\[a-zA-Z]{1}\$(?!.)

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