Java regex pattern with optional string

I have lines like these:

something something [[abcd]] blah blah
something something [[xyz|abcd]] blah blah

In both cases, I want:

something something abcd blah blah

How to do this using only 1 regex pattern in Java? I can do the first case with this:

Pattern pattern = Pattern.compile("\\[\\[(.+?)\\]\\]");
Matcher m = patternLinkRemoval.matcher(text);
return m.replaceAll("$1");
+5
source share
2 answers

Add the following:

  • All but |zero or more:[^|]*
  • ... and then |:|
  • ... additionally: ?
  • Group it using (?: ... )if you don't want to record it.

Here is a complete example:

String text1 = "something something [[abcd]] blah blah";
String text2 = "something something [[xyz|abcd]] blah blah";

Pattern pattern = Pattern.compile("\\[\\[(?:[^|]*\\|)?(.+?)\\]\\]");

System.out.println(pattern.matcher(text1).replaceAll("$1"));
System.out.println(pattern.matcher(text2).replaceAll("$1"));

Conclusion:

something something abcd blah blah
something something abcd blah blah
+3
source

Found it myself! \\[\\[(?:.+?\\|)?(.+?)\\]\\]

0
source

All Articles