I try to figure out how to get 2 matches from String Bla bla bla [https://google.com|Google] bla bla bla [https://youtube.com|Youtube]
I want to get 2 matches: [https://google.com|Google], [https://youtube.com|Youtube].
My regex looks likee this: \[.*\|.*\] and with it I get only one match: [https://google.com|Google] bla bla bla [https://youtube.com|Youtube] so it is wrong answer. How to get the right answer?
P.S. google and youtube - the hardcoded example. I get array of data with 1000+ entries, so I need a universal solution.
You can use
\[([^\]\[|]*)\|([^\]\[]*)]
See the regex demo. Details:
\[ - a [ char([^\]\[|]*) - Group 1: any zero or more chars other than [, ] and |\| - a | char([^\]\[]*) - Group 2: any zero or more chars other than [ and ]] - a ] char.In Java, use
String regex = "\\[([^\\]\\[|]*)\\|([^\\]\\[]*)]";
See the Java demo:
String s = "Bla bla bla [https://google.com|Google] bla bla bla [https://youtube.com|Youtube]";
String regex = "\\[([^\\]\\[|]*)\\|([^\\]\\[]*)]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println("Match: " + matcher.group(0));
System.out.println("Group 1: " + matcher.group(1));
System.out.println("Group 2: " + matcher.group(2));
}
Output:
Match: [https://google.com|Google]
Group 1: https://google.com
Group 2: Google
Match: [https://youtube.com|Youtube]
Group 1: https://youtube.com
Group 2: Youtube
u need to make quantifier * lazy by adding ? mark , here is an example :
String s = "Bla bla bla [https://google.com|Google] bla bla bla [https://youtube.com|Youtube]";
Pattern p = Pattern.compile("\\[.*?\\]");
Matcher matcher = p.matcher(s);
while(matcher.find()){
System.out.println(matcher.group());
}
OUTPUT :
[https://google.com|Google]
[https://youtube.com|Youtube]