Reputation: 36304
Ok. I know that i am missing something. I am just not able to find out what I am missing. The below mentioned pattern matches "|" and i don't know why. Can someone please explain. thanks. I want to match a single character. The character set is {,},[,],|,? etc.
public static void main(String[] args) {
String str = "";
if (str.matches("[\"|`|+|,|;|<|>|?|\\[|\\]|{|}|']"))
System.out.println("matches");
}
Upvotes: 0
Views: 72
Reputation: 8591
You are mixing up two different ways of specifying alternatives:
[]
)|
)Pick one.
Upvotes: 0
Reputation: 1195
In short, You have given | in the [ ] brackets.
Any character within square brackets[ ] will be matched.
Remove all the | inside the braces.
Upvotes: 0
Reputation: 13866
You don't need to use the |
sign in the regex, because you're using an array of characters to match to. Basically if you want to match something to a,b,c or d
, which means that the string can contain any of those letters you can simply do
String pattern = "[abcd]*"; // * means they can be repeated, for example "aabdcb"
str.matches(pattern);
No need to use the pipe. On the other hand if you want to strictly say that a string is either a or b
you can use a pattern like
pattern = "(a)|(b)"; // matches either "a" or "b"
Hope this clears up things a bit for you.
You might want to check out this page to learn more about using pipe in regexes.
Upvotes: 2
Reputation: 66886
You are using []
to start and end the expression, when it looks like you are using syntax that goes with ()
. The square braces let you list a bunch of characters that match, and |
is in your list many times. Parentheses set up a grouping inside which you can use |
to mean "or".
I think the solution for you is to remove those |
. You don't separate characters inside square braces with anything, you just list them all.
Upvotes: 3