Regex find substring

Let's say that I have a substring BB, which can be one or part of a longer string, for example. BB or AA | BB | CC or BB | CC or AA | BB, that is, if followed by /, another substring follows that MUST be divided by |. What regular expression do I need to find BB in any of the above, but not in AABB?

+5
source share
4 answers

I think this will do:

^(.+[|])?BB([|].+)?$

And after testing here, I'm going to say yes, that's it.

+6
source

If your substrings are limited to alphanumeric characters, you can use:

\bBB\b

, , :

(?<=\||^)BB(?=\||$)

.

+4

:

Pattern p = Pattern.compile("(?<![^|])BB(?![^|])");

String[] input = { "AABB", "BB", "AA|BB|CC", "BB|CC", "AA|BBB", "BBB|AA" };
for (String s : input)
{
  Matcher m = p.matcher(s);
  System.out.printf("%-10s : %b%n", s, m.find() );
}

:

AABB       : false
BB         : true
AA|BB|CC   : true
BB|CC      : true
AA|BBB     : false
BBB|AA     : false

, @Kobi, , BB IS / / , , / , .

+3

, , , , BB, BB '|' :

String data = "AA|BB|CCBBCC|BB";
Matcher m = Pattern.compile("(BB)(?:\\||$)").matcher(data);
while (m.find()) {
    System.out.println(m.group(1) + " starts at " + m.start() + " ends at " + m.end(1));
}
0

All Articles