簡體   English   中英

簡單的Java正則表達式匹配和替換

[英]Simple java regex match and replace

所以我有包含字符串的myString

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

我想使用正則表達式來檢查它是否包含"width:8px" (\\bwidth\\s*:\\s*(\\d+)px)

如果為true,則將寬度值(例如,上面的示例為8)添加到myList中。

嘗試:

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

有什么幫助嗎?

編輯:所以我研究了contains方法,發現它不允許使用正則表達式。 matches將允許使用正則表達式,但它將查找完全匹配項。

您需要為此使用Matcher#find()方法。

從文檔中:-

嘗試找到與模式匹配的輸入序列的下一個子序列。

然后您可以從中獲取捕獲的組:-

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

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

您必須使用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");
}

您的主要問題是contains()不接受正則表達式,而是接受文字字符串。
另一方面 matches() 確實接受正則表達式參數,但必須匹配整個字符串才能返回true。

接下來,一旦找到匹配項,就可以使用replaceAll()提取目標內容:

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

這將用原始正則表達式捕獲的組#1的內容替換整個輸入String。

請注意,我從原始匹配的正則表達式中刪除了多余的括號,但將其留作替換以捕獲目標內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM