You did not state if you have nested patterns, so here is an example to start you off.
You need to double escape \\
here since \
is also an escape character for strings.
String s = "This is a test [url] http://www.google.com.hk [/url]\n"
+ " and [img] http://www.abc.com/test.png [/img]";
Pattern p = Pattern.compile("\\[[^\\]]*\\]([^\\]]*)\\[[^\\]]*\\]");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group(1).trim());
}
See working demo
Regular expression:
\[ '['
[^\]]* any character except: '\]' (0 or more times)
\] ']'
( group and capture to \1:
[^\]]* any character except: '\]' (0 or more times)
) end of \1
\[ '['
[^\]]* any character except: '\]' (0 or more times)
\] ']'
If you want to be specific on img
or url
code tags, you could use the following.
Pattern p = Pattern.compile("(?i)\\[(?:url|img)\\]([^\\]]*)\\[\\/(?:url|img)\\]");