i want a regular expression to validate string to have only text,operators and these brackets ([ ])
views:
58answers:
3
+1
A:
To match these characters:
if (str.matches("[a-zA-Z\\[\\]+\\-/*()]*")) {
...
}
A better version is:
if (str.matches("\\s*\\[[a-zA-Z]+\\](\\s*[/*+-]\\s*\\[[a-zA-Z]+\\])*")) {
...
}
Supporting parentheses is difficult because if you can put expressions in parentheses it is no longer a regular language (it is a context-free language). Regexes are a poor fit for matching that kind of expression. For that you'll need a PDA (pushdown automaton).
cletus
2010-03-30 04:55:48
i jst want + ,- *,/ as operators and ([ ]) and text
sarah
2010-03-30 05:04:37
it shld match ([price] + [test])
sarah
2010-03-30 05:06:37
+1
A:
I strongly encourage you to look at, and use, http://www.regexbuddy.com/.
Jordan S. Jones
2010-03-30 04:56:08
A:
String foo = "[price] + [test]";
System.out.println(foo.matches("\\[[a-zA-Z]+\\] ?[+/*-] ?\\[[a-zA-Z]+\\]"));
and if you want to include the parentheses in the String:
String foo = "([price] + [test])";
System.out.println(foo.matches("\\(\\[[a-zA-Z]+\\] ?[+/*-] ?\\[[a-zA-Z]+\\]\\)"));
Rob Heiser
2010-03-30 05:31:02