简体   繁体   中英

Java Regular Expressions Capturing Groups

I want to split width and height from this String

String imgStyle = "width: 300px; height: 295px;";
int width = 300; // i want to get this value
int height = 295; // i want to get this value

I tried a lot of regular expressions but i can't get them.

String imgStyle = "width: 300px; height: 295px;";

int imgHeight = 0;
int imgWidth = 0;

Pattern h = Pattern.compile("height:([0-9]*);");
Pattern w = Pattern.compile("width:([0-9]*);");

Matcher m1 = h.matcher(imgStyle);
Matcher m2 = w.matcher(imgStyle);

if (m1.find()) {
    imgHeight = Integer.parseInt(m1.group(2));
}

if (m2.find()) {
    imgWidth = Integer.parseInt(m2.group(2));
}

java.lang.IllegalStateException: No successful match so far

In the simplest case:

public static void main(String[] args) {
    final String imgStyle = "width: 300px; height: 295px;";
    final Pattern pattern = Pattern.compile("width: (?<width>\\d++)px; height: (?<height>\\d++)px;");
    final Matcher matcher = pattern.matcher(imgStyle);
    if (matcher.matches()) {
        System.out.println(matcher.group("width"));
        System.out.println(matcher.group("height"));
    }
}

Simply replace the number part with (\\\\d++) - ie match and capture the digits.

I have used named groups for clarity.

Try something like:

String imgStyle = "width: 300px; height: 295px;";
Pattern pattern = Pattern.compile("width:\\s+(\\d+)px;\\s+height:\\s+(\\d+)px;");
Matcher m = pattern.matcher(imgStyle);
if (m.find()) {
    System.out.println("width is " + m.group(1));
    System.out.println("height is " + m.group(2));
}

The pattern is wrong:

Pattern h = Pattern.compile("height:([0-9]*);");
Pattern w = Pattern.compile("width:([0-9]*);");

In your string, there is a space between the colon and the number, and you also have px before the semicolon, so it should be:

Pattern h = Pattern.compile("height: ([0-9]*)px;");
Pattern w = Pattern.compile("width: ([0-9]*)px;");

Or better:

Pattern h = Pattern.compile("height:\\s+(\\d+)px;");
Pattern w = Pattern.compile("width:\\s+(\\d+)px;");

You should also capture group 1, not group 2:

if (m1.find()) {
    imgHeight = Integer.parseInt(m1.group(1));
}

if (m2.find()) {
    imgWidth = Integer.parseInt(m2.group(1));
}

DEMO

Just add space before the digits:

Pattern h = Pattern.compile("height:\\s*([0-9]+)");
Pattern w = Pattern.compile("width:\\s*([0-9]+)");

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