简体   繁体   中英

Java regex return after first matched pattern

I want to extract word after first 'from' in the following string-

"anti-CD24 from Chemicon, and anti-CD48 from Santa"

Right now, I am using -

"from\\s+([^\\s]+)"

But it is giving both results 'Chemicon' and 'Santa' instead of only 'Chemicon'.

Maybe you could do something like this:

    Pattern p = Pattern.compile("from\\s+([^\\s]+)");
    Matcher m = p.matcher("anti-CD24 from Chemicon, and anti-CD48 from Santa");
    if (m.find()) {
        System.out.println(m.group(1));
    }

This would take just the first one. And maybe you could use this regular expression to avoid the comma for the first match ( Chemicon, ): from\\\\s+([a-zA-Z]+)

You can use the lookingAt method on the Method object. It stops after it finds the first match.

Like the matches function and unlike the find function lookingAt has to match from the beginning, so we have to use the regex ".*?from\\\\s+(\\\\w+)" , which says: match anything up until the first "from", then one or more whitespace chars, then the next "word". If you only want alphabetical chars to match your word after "from" then use ".*?from\\\\s+([a-zA-Z])" . The ".*?" at the beginning means non-greedy matching. If you just use ".*" it will match the last "from", not the first one.

Here's code that I've tested:

  String s = "anti-CD24 from Chemicon, and anti-CD48 from Santa";
  Matcher m = Pattern.compile(".*?from\\s+(\\w+)").matcher(s);
  if (m.lookingAt()) {
    System.out.println(m.group(1));
  }

Prints out:

Chemicon

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