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.
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));
}
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With