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");
Add the following:
|
zero or more times: [^|]*
|
: |
?
(?: ... )
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With