How does this regex work?

System.out.println("du hast mich".replaceAll("(?<=^(.*)) ", ", $1 "));
// prints "du, du hast, du hast mich"

What does the symbol mean ^after it looks? (I know that the standard value of this symbol is the beginning of a line), and why the dot symbol matches what it was then, and then, yes, that is. Why does the dot character not match the entire string?

Please give me an explanation of how this regular expression works correctly. I wonder. Thank you for your interest.

+4
source share
3 answers

(?<= )is the lookbehind syntax . ^- it's just the "beginning of the line." Essentially what the regular expression says:

" , . , , .

+3

. .

du hast mich
 ^ regex hasn't matched anything so no replacement

du

du hast mich
  ^ regex matches

, du

du hast mich
      ^ no match

hast

du hast mich
       ^ regex matches

, du hast

du hast mich
           ^ no match

mich

,

du, du hast, du hast mich
+2

. - (.*) lookbehind. , , . ! , .

Java lookbehind has always been a little twitchy, which I attribute to its complex well-known maximum length requirement for lookbehind subexpressions. I came to the conclusion that this function was a mistake; it is simply not useful in order to justify the fuss he brought with him. That is why I try to avoid using any quantifiers in my searches.

0
source

All Articles