Ibrahim Disouki
Ibrahim Disouki

Reputation: 2693

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

Upvotes: 0

Views: 200

Answers (4)

Toto
Toto

Reputation: 91518

Just add space before the digits:

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

Upvotes: 0

BackSlash
BackSlash

Reputation: 22243

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

Upvotes: 0

SMA
SMA

Reputation: 37103

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));
}

Upvotes: 1

Boris the Spider
Boris the Spider

Reputation: 61198

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++) - i.e. match and capture the digits.

I have used named groups for clarity.

Upvotes: 1

Related Questions