简体   繁体   中英

java string matching with regex

I have a specific key i need to match. The key is 10 set's of 4 separated by a dash. The combination can be a combination of letters or numbers.

Example.

aa11-bb22-cc33-44dd-55ee-66ff-gg77-hh88-99ii-jj10

I just want to validate the pattern being 10 sets of 4 separated by a dash.

Probably match this via regex, but I don't know how.

Any help would be appreciated.

^[a-zA-Z0-9]{4}(?:-[a-zA-Z0-9]{4}){9}$

Try this.See demo.

http://regex101.com/r/kP8uF5/11

([a-zA-Z0-9]{4}-){9}[a-zA-Z0-9]{4}

Here's the regex in action: http://regex101.com/r/xR1wV3/1

Explanation:

  1. [a-zA-Z0-9] --> any character from a to z, A to Z and 0 to 9
  2. [a-zA-Z0-9]{4} --> {4} indicates exactly 4. So [a-zA-Z0-9]{4} means exactly 4 characters
  3. [a-zA-Z0-9]{4} - --> add a dash (-) at the end to match for dash separators. This should match with aa11- for example
  4. ([a-zA-Z0-9]{4}-) --> put #3 into parenthesis
  5. ([a-zA-Z0-9]{4}-){9} --> add {9} to the parenthesis to specify that this pattern repeat 9 times
  6. ([a-zA-Z0-9]{4}-)[a-zA-Z0-9]{4} --> add a [a-zA-Z0-9]{4} at the end to match the last set of 4 characters (same as #2 above)

You could do it like this:

(?!.*_)(\w{4}-){9}\w{4}

This makes use of the fact that \\w means "any letter, number or underscore" and the negative look ahead prevents the underscore.

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