Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex pattern with optional string

Tags:

java

regex

I have strings like these:

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

What I want in both cases is:

something something abcd blah blah

How do I 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");
like image 719
pckben Avatar asked Jun 19 '12 13:06

pckben


1 Answers

Add the following:

  • Anything except | zero or more times: [^|]*
  • ...followed by a |: |
  • ...optionally: ?
  • Group it using (?: ... ) if you don't want to capture the thing.

Here's 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"));

Output:

something something abcd blah blah
something something abcd blah blah
like image 149
aioobe Avatar answered Oct 02 '22 18:10

aioobe