apines
apines

Reputation: 1262

regex - disallowing a sequence of characters

I have a variable in the form of {varName} or {varName, "defaultValue"} and I want a regex that will match it. varName is only alphanumeric and "_" (\w+), and the default value can be anything except the combination of "} which signifies the end of the variable. White space doesn't matter between the braces, comma, varName or defaultValue. So far the regex that I have come up with is

\{\s*(\w+)\s*(,\s*\"([^(\"\})]*)\"\s*)?\}

The problem is that the match ends at the first " OR } and not the combination, i.e. {hello, "world"} does match but {hello, "wor"ld"} or {hello, "wor}ld"}

Any idea how to solve this? In case this helps, I'm coding it using Java.

Upvotes: 1

Views: 245

Answers (2)

apines
apines

Reputation: 1262

I have found the solution to my own question, it's only fair to share. The following regex:

\{\s*(\w+)\s*(,\s*\"((.*?)\s*\")?\})

Will do the trick, stopping at the first sequence of '"}'

In Java, this will be (continuing previous answer's example):

final Pattern p = Pattern.compile("\\{\\s*(\\w+)\\s*(,\\s*\"(.*?)\\s*\"\\s*)?\\}");
Matcher m1 = p.matcher("{hello, \"world\"}");
if (m1.matches()) {
    System.out.println("var1:" + m1.group(1));
    System.out.println("val1:" + m1.group(3));
}
Matcher m2 = p.matcher("{hello, \"wor\"rld\"}\"}");
if (m2.matches()) {
    System.out.println("var2:" + m2.group(1));
System.out.println("val2:" + m2.group(3));
}

/* Output
var1:hello
val1:world
var2:hello
val2:wor"rld"}
*/

Upvotes: 1

mana
mana

Reputation: 6547

final Pattern p = Pattern.compile("\\{\\s*(\\w+)\\s*(,\\s*\"((?!\"\\}).*)\"\\s*)?\\}");
Matcher m1 = p.matcher("{hello, \"world\"}");
if (m1.matches()) {
    System.out.println("var1:" + m1.group(1));
    System.out.println("val1:" + m1.group(3));
}
Matcher m2 = p.matcher("{hello, \"wor}ld\"}");
if (m2.matches()) {
    System.out.println("var2:" + m2.group(1));
    System.out.println("val2:" + m2.group(3));
}
Matcher m3 = p.matcher("{hello, \"wor}\"ld\"}");
if (m3.matches()) {
    System.out.println("var3:" + m3.group(1));
    System.out.println("val3:" + m3.group(3));
}

/*output: 
var1:hello
val1:world
var2:hello
val2:wor}ld
var3:hello
val3:wor}"ld */

Upvotes: 1

Related Questions