简体   繁体   中英

Get word between two numbers java regex

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

eg 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 eg Car

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM