简体   繁体   中英

extract specific word from comma separated string in java using regex

input - [1, 1111, 2020, BMW, Frontier, EXTENDED CAB PICKUP 2-DR, Silver, 16558] I want to extract here BMW and I am using (^(?:[^\\,]*\\,){3}) this regex. This results into - BMW, Frontier, EXTENDED CAB PICKUP 2-DR, Silver, 16558] . Could any one help me with this? thanks in advance

If it is comma seperated string, you could just split function from the string class which would convert the comma seperated string to array. Refer - Link

The string split() method breaks a given string around matches of the given regular expression.

Syntax - Public String [ ] split ( String regex, int limit )

Input String: 016-78967
Regular Expression: -
Output : {"016", "78967"}

Then you could into the array to find out the particular keyword from it.

As you can only enter a pattern without making use of groups, you could make use of finite repetition for example {0,1000} in the positive lookbehind as Java does not support infinite repetition.

(?<=^\\[[^,]{0,1000},[^,]{0,1000},[^,]{0,1000},\\h{0,10})\\w{3,10}(?=[^\\]\\[]*\\])

Explanation

  • (?<= Positive lookbehind, assert what is on the left is
    • ^\[ Start of string, match [
    • [^,]{0,1000},[^,]{0,1000},[^,]{0,1000}, Match 3 times any char except , followed by the ,
    • \h{0,10} Match 0-10 times a horizontal whitespace char
  • ) Close lookbehind
  • \w{3,10} Match 3-10 word chars
  • (?= Positive lookahead, assert what is on the right is
    • [^\]\[]*\] Match until the ]
  • ) Close lookahead

Java demo

Code example

final String regex = "(?<=^\\[[^,]{0,1000},[^,]{0,1000},[^,]{0,1000},\\h{0,10})\\w{3,10}(?=[^\\]\\[]*\\])";
final String string = "[1, 1111, 2020, BMW, Frontier, EXTENDED CAB PICKUP 2-DR, Silver, 16558]";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println(matcher.group(0));
}

Output

BMW

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