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

Difference beetwen = and == in regex java

I couldn’t define a regular expression between "=" and "==". To explain more clear, look at the codes.

if(Pattern.matches("(.*)=(.*)", text))
{
        
    // code block 1
}

if(Pattern.matches("(.*)==(.*)", text))
{

    // code block 2
}

Sample text1 : asdasdasd=asdasdasd

Sample text2 : asdasdasd==asdasdasd

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

When the text be like above samples, in any case only code block 1 is working.
Also I know "( .* )=( .* )" this expression is wrong. I tried "(.*)=(^=)" etc. but I couldn’t figure out. I want to find solution which if text has a "=", code block 1 works, if text has "==", code block 2 works.

>Solution :

To exclude a character, that isn’t (^=), but between square brackets [^=], giving either :

  • (.*[^=])=([^=].*)
  • (.*)(?<!=)=(?!=)(.*) with negatives lookahead+lookbehind

Or could work with String.contains, in the right order

if (text.contains("==")) {
    System.out.println("Case 2");
} else if (text.contains("=")) {
    System.out.println("Case 1");
}
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