Reputation: 99
I am trying to get text "STARTS WITH" from following string [DOC TEXT] STARTS WITH [foo] using regex. I have used following code for this.
String expertWhereClause = (String) formFields
.get(Constants.EXPERT_SEARCH_WHERECLAUSE);
String delims = "\\[(.*?)\\]";
String[] tokens = expertWhereClause.split(delims);
but am getting following string "[, STARTS WITH ]". I just want "STARTS WITH".
Am new to regex, please help me out here.
Thanks in advance
Upvotes: 2
Views: 1741
Reputation: 9039
Use this regex:
\]\s*([^\[]*?)\s*\[
You may need to escape the backslashes based on the language you are using.
Update: For Java, escape the backslashes
\\]\\s*([^\\[]*?)\\s*\\[
The desired text is captured in the first group.
Upvotes: 1
Reputation: 726809
You can use Matcher
for this:
Matcher m = Pattern.compile("\\]([^\\[]*)\\[").matcher("[Hello]world[!!!]");
while (m.find()) {
System.out.println(m.group(1));
}
This code fragment prints world
on ideone.
Note how I changed your regex to use [^\\[]*
in place of .*?
. This improves efficiency, which may be important for longer inputs.
Upvotes: 3
Reputation: 785491
If it is Java then you can use this code:
String str = "[DOC TEXT] STARTS WITH [foo] ";
System.out.printf("<%s>%n",
str.replaceAll("^[^\\]]+\\]\\s*([^\\[]+?)\\s*\\[.*$", "$1"));
// output
//<STARTS WITH>
Upvotes: 1