Skip to content
Advertisement

Refactor regex Pattern into Java flavor pattern

I have a regex pattern created on regex101.com: https://regex101.com/r/cMvHlm/7/codegen?language=java

however, that regex does not seem to work in my Java program (I use spring toolsuite as IDE):

JavaScript

I get the following error:

JavaScript

Is there a way to find out where index 1337 is?

Advertisement

Answer

The main problem with the regex is that both [ and ] must be escaped in a character class in a Java regex as these are used to form character class unions and intersections, are “special” there.

Another issue is the [.]b patterns won’t work as expected because a word boundary after a non-word char will require a word char immediately to the right of the current position. You need a B there, not b.

You need to escape / char in a Java regex pattern.

You do not have to repeat the pattern at the end of the regex, you may “repeat” it with a limiting {0,3} quantifier after wrapping the repeated pattern with a non-capturing group, (?:...).

Consider a while block to get all matches. You may use a boolean flag to see if there were any matches or not.

Also, you probably want to use \s+ alternative as the last one in the first group, it is too generic, but I will leave it at the start for the time being.

Use

JavaScript

See this Java demo.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement