meiryo
meiryo

Reputation: 11697

Simple java regex match and replace

So I have myString which contains the string

"border-bottom: solid 1px #ccc;width:8px;background:#bc0b43;float:left;height:12px"

I want to use regex to check that it contains "width:8px" (\bwidth\s*:\s*(\d+)px)

If true, add the width value (i.e. 8 for above example) to my myList.

Attempt:

if (myString.contains("\\bwidth\\s*:\\s*(\\d+)px")) {
    myList.add(valueofwidth) //unsure how to select the width value using regex
}

Any help?

EDIT: So I've looked into contains method and found that it doesn't allow regex. matches will allow regex but it looks for a complete match instead.

Upvotes: 4

Views: 10496

Answers (3)

Bohemian
Bohemian

Reputation: 425358

Your main problem is that contains() doesn't accept a regex, it accepts a literal String.
matches() on the other hand does accept a regex parameter, but must match the entire string to return true.

Next, once you have your match, you can use replaceAll() to extract your target content:

if (myString.matches(".*\\bwidth\\s*:\\s*\\d+px.*")) {
    myList.add(myString.replaceAll(".*\\bwidth\\s*:\\s*(\\d+)px.*", "$1"))
}

This replaces the entire input String with the contents of group #1, which your original regex captures.

Note that I removed the redundant brackets from your original matching regex, but left them in for the replace to capture the target content.

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213391

You need to use Matcher#find() method for that.

From the documentation: -

Attempts to find the next subsequence of the input sequence that matches the pattern.

And then you can get the captured group out of it: -

Matcher matcher = Pattern.compile("\\bwidth\\s*:\\s*(\\d+)px").matcher(myString);

if (matcher.find()) {
    myList.add(matcher.group(1));
}

Upvotes: 6

Javier Diaz
Javier Diaz

Reputation: 1830

You have to use a Matcher and matcher.find():

Pattern pattern = Pattern.compile("(\\bwidth\\s*:\\s*(?<width>\\d+)px)");
Matcher matcher = pattern.matcher(args);
while (matcher.find()) {
    myList.add(matcher.group("width");
}

Upvotes: 4

Related Questions