Reputation: 1045
I am studying regex in Java. After I do some reading I think |
is a special character in regex, but when I try to apply these two functions I find that I can directly use |
in contains function, which should be in the format \\|
in split function. so is there any difference in these two functions in apply regex?
String c = "come|dra";
Pattern regex = Pattern.compile("|");
Matcher matcher = regex.matcher(c);
System.out.println(matcher.find()+" "+c.contains("|"));
String [] s1 = c.split("|");
System.out.println(s1[1]);
output:
true true c
Upvotes: 0
Views: 105
Reputation: 70732
The #String.contains()
method works with only "String". It doesn't work with regular expressions, while the #String.split()
method can split using regular expression as delimiter.
Upvotes: 1
Reputation: 48824
Be careful which methods you're calling. In your example code, you're calling String.contains()
which does not use regular expressions.
Returns true if and only if this string contains the specified sequence of char values.
Certain methods of String
- namely String.matches()
, String.replaceAll()
, String.replaceFirst()
, and String.split()
- are convenient wrappers around the regular expression behaviour Pattern
provides. For example, String.split()
simply* calls:
return Pattern.compile(regex).split(this, limit);
* It actually tries to do some optimizations before reaching this line, but in the general case, that's what it does.
Upvotes: 3