Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java non-greedy (?) regex to match string

String poolId = "something/something-else/pools[name='test'][scope='lan1']";
String statId = "something/something-else/pools[name='test'][scope='lan1']/stats[base-string='10.10.10.10']";

Pattern pattern = Pattern.compile(".+pools\\[name='.+'\\]\\[scope='.+'\\]$");

What regular expression should be used such that

pattern.matcher(poolId).matches()

returns true whereas

pattern.matcher(statsId).matches()

returns false?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note that

  1. something/something-else is irrelevant and can be of any length
  2. Both name and scope can have ANY character including any of \, /, [, ] etc
  3. stats[base-string='10.10.10.10'] is an example and there can be anything else after /

I tried to use the non-greedy ? like so .+pools\\[name='.+'\\]\\[scope='.+?'\\]$ but still both matches return true

>Solution :

You can use

.+pools\[name='[^']*'\]\[scope='[^']*'\]$

See the regex demo. Details:

  • .+ – any one or more chars other than line break chars as many as possible
  • pools\[name=' – a pools[name='string
  • [^']* – zero or more chars other than a '
  • '\]\[scope=' – a '][scope=' string
  • [^']* – zero or more chars other than a '
  • '\] – a '] substring
  • $ – end of string.

In Java:

Pattern pattern = Pattern.compile(".+pools\\[name='[^']*']\\[scope='[^']*']$");

See the Java demo:

//String s = "something/something-else/pools[name='test'][scope='lan1']"; // => Matched!
String s = "something/something-else/pools[name='test'][scope='lan1']/stats[base-string='10.10.10.10']";
Pattern pattern = Pattern.compile(".+pools\\[name='[^']*']\\[scope='[^']*']$");
Matcher matcher = pattern.matcher(s);
if (matcher.find()){
    System.out.println("Matched!"); 
} else {
    System.out.println("Not Matched!"); 
}
// => Not Matched!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading