Java Matcher Get regex match, if one, or blank string.

PreviousNext

Get regex match, if one, or blank string.

Parameter:

  • pattern the regex to find match
  • content the string to apply pattern to

Return:

the matching string (or empty string)

//package com.java2s;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /**/*  ww  w  .    d  e m  o 2    s  .c   o m  */
     * Get regex match, if one, or blank string.
     *
     * @param  pattern the regex to find match
     * @param  content the string to apply pattern to
     * @return the matching string (or empty string)
     */
    public static String getMatch(final String pattern, final String content) {
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(content);

        if (m.find()) {
            return m.group(1);
        } else {
            return "";
        }
    }
}
PreviousNext

Related