Joseph K.
Joseph K.

Reputation: 774

Matching a character which occurs single

I have two strings like this: "A == B", "C = D". I want to find out whether a string contains assignment operator = or equal to == operator. For example "C=D" should returns true and "C=D=D" should returns true as well. But "A==B" should returns false. I tried "[^=][=][^=]" but it is returning false for both strings.

Pattern pattern = Pattern.compile("[^=][=][^=]");
Matcher matcher = pattern.matcher("A=B");

System.out.println(matcher.matches());

This is returning false but I want to get true.

Upvotes: 1

Views: 111

Answers (4)

Alex
Alex

Reputation: 803

In Java, Matcher.match() will try to match the whole string. To just find a sub-string in between, you should use Matcher.find() instead.

Pattern pattern = Pattern.compile("[^=][=][^=]");
Matcher matcher = pattern.matcher("A=B");

System.out.println(matcher.find());

This will return true for any string with single '=' only. And will return false for string containing '=='.

Upvotes: 3

M. le Rutte
M. le Rutte

Reputation: 3563

The corresponding regular expression is "[^=]+=[^=]+", assuming you allow any length and whitespaces before and after the = sign.

jshell> "A=B".matches("[^=]+=[^=]+")
$6 ==> true

jshell> "Ad=Bd".matches("[^=]+=[^=]+")
$7 ==> true

jshell> "Ad==Bd".matches("[^=]+=[^=]+")
$8 ==> false

$jshell> "A==B".matches("[^=]+=[^=]+")
$9 ==> false

jshell> "A cow = an animal".matches("[^=]+=[^=]+")
$10 ==> true

jshell> "    =     ".matches("[^=]+=[^=]+")
$11 ==> true

jshell> "=".matches("[^=]+=[^=]+")
$12 ==> false

jshell> "A==B && A=B".matches("[^=]+=[^=]+")
$13 ==> false

Though given the last example, I wonder if it is not better to use a tool like XText or ANTLR, which provide a better manner at parsing expressions.

Upvotes: 1

Manva Pradhan
Manva Pradhan

Reputation: 11

Trying buiding the Regex again. Use https://regexr.com to solve it. You pattern matches only "A=B" "C=D" "=A=B" and changing it to "[^=][=][^=][=][^=]" will make it recognize "A=B=C" and "A=F=R" or "=A=B=C". Thus check your Regex. enter image description here

Upvotes: 0

Code-Apprentice
Code-Apprentice

Reputation: 83517

You can simply do !myString.contains("==") which will return true if myString does not have ==. If you want to guarantee at least one = then do

myString.contains("=") && !myString.contains("==")

Upvotes: 1

Related Questions