tags:

views:

58

answers:

3

i want a regular expression to validate string to have only text,operators and these brackets ([ ])

+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
i jst want + ,- *,/ as operators and ([ ]) and text
sarah
it shld match ([price] + [test])
sarah
+1  A: 

I strongly encourage you to look at, and use, http://www.regexbuddy.com/.

Jordan S. Jones
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