简体   繁体   中英

Java regular expressions for specific name\value format

I'm not familiar yet with java regular expressions. I want to validate a string that has the following format:

String INPUT = "[name1 value1];[name2 value2];[name3 value3];"; 

namei and valuei are Strings should contain any characters expect white-space.

I tried with this expression:

String REGEX = "([\\S*\\s\\S*];)*";

But if I call matches() I get always false even for a good String.

what's the best regular expression for it?

This does the trick:

(?:\[\w.*?\s\w.*?\];)*

If you want to only match three of these, replace the * at the end with {3} .

Explanation:

  • (?: : Start of non-capturing group

  • \\[ : Escapes the [ sign which is a meta-character in regex. This allows it to be used for matching.

  • \\w.*? : Lazily matches any word character [az][AZ][0-9]_ . Lazy matching means it attempts to match the character as few times possible, in this case meaning that when will stop matching once it finds the following \\s .

  • \\s : Matches one whitespace

  • \\] : See \\[

  • ; : Matches one semicolon

  • ) : End of non-capturing group

  • * : Matches any number of what is contained in the preceding non-capturing group.

See this link for demonstration

You should escape square brackets. Also, if your aim is to match only three, replace * with {3}

(\[\\S*\\s\\S*\];){3}

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