Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple java regex match and replace

Tags:

java

regex

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.

like image 260
meiryo Avatar asked Dec 20 '22 11:12

meiryo


2 Answers

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));
}
like image 73
Rohit Jain Avatar answered Jan 01 '23 21:01

Rohit Jain


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");
}
like image 29
Javier Diaz Avatar answered Jan 01 '23 19:01

Javier Diaz