java - Find text in square brackets but not in parentheses -
if have string (from wiki-markup) need parse in java:
this link (is [[ inparen ]] and) (this) 1 [[ notinparen ]] i'd use regex extract texts inside [[ ]] not if inside parentheses. example, in example above should return:
notinparen but ignore:
inparen , ... since inside parentheses. can find parentheses , brackets separately no problem:
.*\(.*?\).* , .*?\[\[(.*?\]\].* ...but can't figure out how find [[ ]], around parentheses, , ignore. thanks!
this fine regex
\(.*?\)|\[\[(.*?)]] your desired match in group 1
fyi, make better perform can minimize backtracking replacing lazy match negated character class.
in java becomes
string resultstring = null; try { pattern regex = pattern.compile("\\(.*?\\)|\\[\\[(.*?)\\]\\]", pattern.dotall | pattern.multiline); matcher regexmatcher = regex.matcher(subjectstring); if (regexmatcher.find()) { resultstring = regexmatcher.group(1); } } catch (patternsyntaxexception ex) { // syntax error in regular expression } note group 1 empty cases first part of alternation did match.
Comments
Post a Comment