Jothi
Jothi

Reputation: 15090

Java RegExp pattern for (

I am trying to form the Regular expressions for the string

Duo Eyeshadow, COMPACT(LID/BASE FRAME ASSY)

Java:

Pattern p = Pattern.compile("\"[a-zA-Z0-9 &/.\\-{()}]+[,][ a-zA-Z0-9&/.\\-{()}]+\"");

The above expression compiles, but is not accepting the ( in the string. Can any one help me for the exact reg for the above string?

I am giving input as string data="Duo Eyeshadow, COMPACT(LID/BASE FRAME ASSY)"

I need the p.matches(data) should be true....,which is not happening

Can someone give me the pattern which allows ( and )

Upvotes: 0

Views: 96

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174786

The below regex would be enough to match the above string Duo Eyeshadow, COMPACT(LID/BASE FRAME ASSY),

"[A-Za-z ]+,[ A-Za-z(/)]+"

Code:

String s = "Duo Eyeshadow, COMPACT(LID/BASE FRAME ASSY)";
boolean out = s.matches("[A-Za-z ]+,[ A-Za-z(/)]+");
System.out.println(out); //=> true

OR

String s = "DuoEyeshadow,COMPACTLI(DBAS)EFRAMEASSY";
boolean out = s.matches("[a-zA-Z0-9 &/.{()}-]+,[ a-zA-Z0-9&/.{()}-]+");
System.out.println(out); //=> true

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328734

I found the easiest way to match ( and ) in regexps is to use [(] and [)]. This works with most regexp engines, is pretty easy to read and doesn't blow up unexpectedly.

The other option is \( but that has to become "\\(" when you use it in strings (to escape the backslash which has a special meaning in Java Strings; totally unrelated to regexp but gets in the way).

And in some regexp slang, \( actually means the same as ( in the Java regexp engine (i.e. the start of a group) which makes things even more confusing which is another reason why I try to avoid it.

Upvotes: 0

Related Questions