简体   繁体   中英

Regex to capture word before matched pattern in Java

I tried to capture word before matched pattern. My search word is "ale". I have to get the word before ale

Input

"Golden pale ale by @KonaBrewingCo @ Hold Fast Bar", 

I want Golden pale words only. Just to get words before matched pattern.

String pattern = "\w+\s" + "ale";
Pattern regex = Pattern.compile(pattern); 
Matcher m = regex.matcher(stat);
if(m.find()){ Do something }

But it shows me error in Java. Anyone help please!!!

If your search string should appear as part of another word, you need to add \\w* before ale :

String keyword = "ale";
String rx = "\\w+\\s+\\w*" + keyword;
Pattern p = Pattern.compile(rx);
Matcher matcher = p.matcher("Golden pale ale by @KonaBrewingCo @ Hold Fast Bar");
if (matcher.find()) {
    System.out.println(matcher.group(0)); // => Golden pale
}

See IDEONE demo

Pattern explanation :

  • \\w+ - 1 or more alphanumeric or underscore characters
  • \\s+ - 1+ whitespaces ( \\W+ will match even punctuation, and other non-word chars)
  • \\\\w* - zero or more word characters (optional part before ....
  • ale - a literal character sequence.

The character \\ is an escape character. You need to do something like this:

String pattern = "\\w+\\s" + "ale";

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