Karanam Krishna Karanam Krishna - 1 month ago 4
Java Question

How to get exact match of & in the given string

Example:

"True && False & True"


In the above string I am trying to match if only
&
is present and not looking for consecutive characters (
&
).

I mean
&&
should not be matched but It should match only
&
if it is available in the string.

In the aforementioned case I should get only 1 match since its available.

I am looking for a regular expression.

Tried Options:

(?=&{1})


I believe by using length of string and finding the first occurrence of
&
and counting the same will give the result.

But still looking for a better answer in form of regular expressions.

Answer

You can use negative lookahead and lookbehind:

(?<!&)&(?!&)

This means "An & not preceded or followed by another &"

Sample Java code :

public static void main(String[] args) {
    String s = "True && False & True but & is & right?";
    Pattern p = Pattern.compile("(?<!&)&(?!&)");
    Matcher m = p.matcher(s);
    while (m.find()) {
    // can keep counter and add +1 here
        System.out.println(m.group());
    }

}

O/P :

&
&
&
Comments