I made the following code:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.Math; // headers MUST be above the first class
// one class needs to have a main() method
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
String ori = "kdya";
String pa = "[kd]";
Pattern pat = Pattern.compile(pa);
Matcher mat = pat.matcher(ori);
System.out.println(mat.matches());
}
}
I want to match the start of the original String (the first character) with any character in the pattern list.
It doesn't match, but it does exist. It's wrong?
The method
Matcher#matches()
tries to match a regex to a text completely, from beginning to end. There are practically no cases where one should use this method.Instead, for standard regular expression behavior, and to be able to match anywhere in the text, the
Matcher#find()
.In regex, the special character
^
matches the position at the beginning of the text (see in the description of Pattern ).Demo en ideone
Your regex accepts strings of length 1 that contain k or s.
Try with
String original = "k";
and you will see that it prints true.In order for your regex to accept any string that starts with k or by s you must use:
(*) Whether or not it accepts line terminators is configurable, but this is off topic.