Home > Mobile >  Get word between two numbers java regex
Get word between two numbers java regex

Time:05-20

I want to get the name word between the first id and before the second number. I want to do this in Java Regex.

e.g. Car Care or Car Electronics & Accessories

#   Name    Id  Child nodes
1   Car Care    15718271    Browse 

2   Car Electronics & Accessories   2230642011  Browse

3   Exterior Accessories    15857511    Browse

I tried splitting the line with .split(" ")[1] but then it splits the words with spaces. Only gives one word within a phrase e.g. Car

CodePudding user response:

Try this one:^\d*[a-zA-Z & -]*(\d*)[a-zA-Z ]* In the match '(\d*)' you will find the wished number. If the strings before and after the number have special characters add them to the appropiate [] sections. Explaination: '^' says start from the beginning, '\d*' take the first digit one or multiple times, [a-zA-Z & -] take a string with these characters, (\d*) specifies the wished number, [a-zA-Z ] again takes a string after the number. Use a regex editor for trying this out.

CodePudding user response:

You can use

(?m)^\d \s (.*?)\s \d{6,}\s

See the regex demo. Details:

  • (?m) - a multiline option
  • ^ - start of a line
  • \d - one or more digits
  • \s - one or more whitespaces
  • (.*?) - Group 1: zero or more chars other than line break chars as few as possible
  • \s - one or more whitespaces
  • \d{6,} - six or more digits
  • \s - a whitespace.

See the Java demo:

String s = "#   Name    Id  Child nodes\n1   Car Care    15718271    Browse \n2   Car Electronics & Accessories   2230642011  Browse\n3   Exterior Accessories    15857511    Browse";
Pattern pattern = Pattern.compile("(?m)^\\d \\s (.*?)\\s \\d{6,}\\s");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println(matcher.group(1)); 
}

Output:

Car Care
Car Electronics & Accessories
Exterior Accessories
  • Related