I am currently working on creating a regex to split out all occurrences of Strings that match the following format: &[ text ] and need to get at the text . Strings could look like: something &[ text ] &[ text ] anything &[ text ] etc.
I have tried the following regex but I cannot seem to get it to work: &\\[(.*)\\]
Any help would be greatly appreciated.
Brackets are a bit tricky regarding escaping. Try this:
Pattern r = Pattern.compile("&\\[([^\\]]*)\\]");
Matcher m = r.matcher("foo &[bla] [foo] &[blub]&[blab]");
while (m.find()) {
System.out.println("Found value: " + m.group(1));
}
I replaced your dot with a group of any sign that is not a closing bracket. The star operator would otherwise greedily match until the very end of the string. You could also suppress the greedy matching with a question mark, this reads even better: "&\\\\[(.*?)\\\\]"
Two things you need to do:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) { String s = "&[test] something ] something &[test2]"; Pattern pattern = Pattern.compile("&\\\\[([^\\\\[\\\\]]*)\\\\]"); Matcher matcher = pattern.matcher(s); while (matcher.find()) { System.out.println("capture group: " + matcher.group(1)); } } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.