Match a letter at the beginning of the string


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); 


I want to match the start of the original String (the first character) with any character from the pattern list.

It does not match, but it does exist. What is wrong?

asked by deluf 12.05.2017 в 22:45

2 answers


Your regex accepts strings of length 1 that contain the k or the s.
Test with String original = "k"; and you'll see that it prints true.

For your regex to accept any string that starts with k or s you should use:


[ks] Acepta un solo caracter de entre los especificados.
.    Acepta cualquier carácter. Pero solo 1. (*)
*    Modifica el elemento anterior (el .) haciendo que acepte
    cualquier cantidad de 0 a infinito.

(*) Whether or not you accept line terminators is configurable but this is removed from the topic.

answered by 12.05.2017 / 23:13

The method Matcher#matches() attempts a regex to match a text completely, from beginning to end. There are practically no cases in which one should use this method.

On the other hand, for the standard behavior of regular expressions, and to be able to find matches anywhere in the text, the method is used Matcher#find() .

In regex, the special character ^ matches the position at the beginning of the text (see in the description of Pattern ).

import java.util.regex.Matcher; 
import java.util.regex.Pattern;
String texto = "kdya"; 
String regex = "^[kd]"; 
Pattern pat  = Pattern.compile(regex); 
Matcher mat  = pat.matcher(texto);

if (mat.find())  // ⬅️⬅️⬅️ Se compara con .find()
    System.out.println("El texto '" + texto + "' empieza con " +; 
    System.out.println("No coincide");

Demo in ideone


Note: I understand that it is a case with which you are practicing. Otherwise, it is much easier to use String#startsWith :

if (texto.startsWith("k") || texto.startsWith("d")) {
answered by 13.05.2017 в 01:39