Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid regular expression

I am trying to match my pattern with an address on java.

String regex = "[a-zA-Z0-9,\\.\']";
if(!address.matches(regex)) {
  //do something
}

Basically, I'm hoping to detect all special characters except for ,, ., '. With the code above, my address

4700 Keele Street, North York, ON

enters the if condition when it should not. Why is this happening ? Also how do you escape a special character ? Shouldn't it be \$? Eclipse IDE prompts an error stating

"Invalid escape sequence (valid ones are \b \t \n \f \r \” \' \ )"

when I do \$ or \^.

like image 370
Kyle Avatar asked Feb 24 '23 11:02

Kyle


2 Answers

I don't believe you need to escape most characters inside of a set. As already mentioned, you'll want to include a space and capture 1 or more of them with a '+':

String regex = "[a-zA-Z0-9,.' ]+";
like image 118
pbaumann Avatar answered Mar 03 '23 00:03

pbaumann


Try this.

[a-zA-z0-9,'\\.\s]

You will also want to match spaces. Your expression is not including spaces, thus the address is not matching.

like image 28
Matt MacLean Avatar answered Mar 03 '23 00:03

Matt MacLean