0

i am trying to extract "d320" from the below string using regex in java using the below code n-us; micromax d320 build/kot49h)

    String m = "n-us; micromax d320 build/kot49h) ";
    String pattern = "micromax (.*)(\\d\\D)(.*) ";
    Pattern r = Pattern.compile(pattern);
    Matcher m1 = r.matcher(m);
    if (m1.find()) {
        System.out.println(m1.group(1));


    }

but it is giving me the output as "d320 build/kot4" , i want only d320

Mohit H
  • 927
  • 3
  • 11
  • 26

2 Answers2

1

Try to use micromax\\s(.*?)\\s like this:

     String m = "n-us; micromax d320 build/kot49h) ";
    String pattern = "micromax\\s(.*?)\\s";
    Pattern r = Pattern.compile(pattern);
    Matcher m1 = r.matcher(m);
    if (m1.find()) {
        System.out.println(m1.group(1));

    }

Output:

  d320
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
0

It's not known whether you want the word after "micromax", or the word that starts with a letter and has all digits afterward, so here's both solutions:

To extract the word following "micromax":

String code = m.replaceAll(".*micromax\\s+(\\w+)?.*", "$1");

To extract the word that looks like "x9999":

String code = m.replaceAll(".*?\b([a-z]\\d+)?\b.*", "$1");

Both snippets will result in a blank string if is there's no match.

Bohemian
  • 412,405
  • 93
  • 575
  • 722