简体   繁体   English

简单的Java正则表达式匹配和替换

[英]Simple java regex match and replace

So I have myString which contains the string 所以我有包含字符串的myString

"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) 我想使用正则表达式来检查它是否包含"width:8px" (\\bwidth\\s*:\\s*(\\d+)px)

If true, add the width value (ie 8 for above example) to my myList. 如果为true,则将宽度值(例如,上面的示例为8)添加到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. 编辑:所以我研究了contains方法,发现它不允许使用正则表达式。 matches will allow regex but it looks for a complete match instead. matches将允许使用正则表达式,但它将查找完全匹配项。

You need to use Matcher#find() method for that. 您需要为此使用Matcher#find()方法。

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(): 您必须使用Matcher和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");
}

Your main problem is that contains() doesn't accept a regex, it accepts a literal String. 您的主要问题是contains()不接受正则表达式,而是接受文字字符串。
matches() on the other hand does accept a regex parameter, but must match the entire string to return true. 另一方面 matches() 确实接受正则表达式参数,但必须匹配整个字符串才能返回true。

Next, once you have your match, you can use replaceAll() to extract your target content: 接下来,一旦找到匹配项,就可以使用replaceAll()提取目标内容:

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. 这将用原始正则表达式捕获的组#1的内容替换整个输入String。

Note that I removed the redundant brackets from your original matching regex, but left them in for the replace to capture the target content. 请注意,我从原始匹配的正则表达式中删除了多余的括号,但将其留作替换以捕获目标内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM