Finding words in brackets that contain a single char using regex
I'm trying to find all words which are enclosed in double brackets and contain a bracket in the middle of the 开发者_高级运维word, I am using Java.
I have this so far but its not quite working.
\\[\\[[\\[|\\]]\\]\\]
Any suggestions?
For this sample input "hello [[wo[orld]]"
, I'd like to find "[[wo[orld]]"
.
This should do:
String str = "hello [[wo[orld]]";
Pattern p = Pattern.compile("\\[\\[[^\\[\\]]*[\\[\\]][^\\[\\]]*\\]\\]");
Matcher m = p.matcher(str);
if (m.find())
System.out.println(m.group(0));
Output:
[[wo[orld]]
Pattern breakdown:
\[\[
-- Two initial[[
(you got that right already!)[^\[\]]*
-- Something else than[
and]
zero or more times[\[\]]
-- The "middle" bracket symbol[^\[\]]*
-- Something else than[
and]
zero or more times\]\]
-- Two closing]]
(that one you figured out as well)
If you want to capture what's in the double brackets and if you don't care whether or not there are other non-bracket characters around the single bracket, try:
(\[\[[^\[\]]*\[[^\[\]]*\]\])
Otherwise, if there must be at least one non-bracket character around the innermost bracket, change the asterisks to plusses, aka:
(\[\[[^\[\]]+\[[^\[\]]+\]\])
The term bracket is a bit overloaded but I assume you are trying to match strings of the form:
[[some[thing]]
String sampleString = "[[some[thing]]";
System.out.println(Pattern.matches("\\[\\[.*\\[.*\\]\\]", sampleString)); //true
Pattern.matches() is a static method that returns true for a match, otherwise false
精彩评论