简体   繁体   中英

Regular Expression to match some strings

I want to find any string from the following set of strings from the user's input:

  • Password@123
  • Pa$$w0rd@123
  • Password#123
  • Pa$$w0rd#123
  • Password_123
  • Pa$$w0rd_123

The digits at the end should be of the min length 3 & max 6. And this is the regex that I wrote:

(Password@(\d{2,6}))|(Pa\$\$w0rd@(\d{2,6}))|(Password#(\d{2,6}))|(Pa\$\$w0rd#(\d{2,6}))|(Password_(\d{2,6}))|(Pa\$\$w0rd_(\d{2,6})).$

I tested my regex on this website and it is not working fine.

It shows "test passed" until the no. of digits reaches 8 (which it shouldn't), and that clearly means that I have made some mistake. I am not an expert in writing Regexes as I am new to this. I don't understand where am I making a mistake.

Your regex should look something like this: ^pa[s5$][s5$]w[o0]rd.\\d{3,6}$ I'm not 100% sure on the C# exact syntax though. I've set up a test suite at regex101 to show you how it works.

This will grab any combination of the string you've given along with 3-6 digits at the end.

https://regex101.com/r/1KaJNz/2

I would recommend using character sets to simplify your regex. This way you don't have to repeat the common logic for every permutation, which, of course is the point of a regex in the first place. With that, I came up with the following:

Pa[s\$]{2}w[o0]rd[@#_]\d{3,6}

You can also add a 5 into the first character set if you want to allow that, as suggested by @JustinMacArthur.

The problem with the regex given in your answer may have something to do with the . at the end which matches any character. This would let any character come after the numbers (including another number) and it would still match.

You can try this regex. Testing of it looks good:

Pa(\$|s){2}w(0|o)rd[@#_]\d{3,6}

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