[英]replace part of a string in java
我正在嘗試編寫一個接受字符串的函數,例如String code = "<div> style="width: 3%" </div>"
我想將3%替換為另一個數字(可以超過2位數字),所以替換為400%等。
我目前正在使用charAt(21),但這只是3的索引,所以如果我在那個地方有20%的代碼,則我的代碼將無法工作。
還有另一種方法可以替換%的存儲位置。 (也可以通過不知道當前百分比是多少來進行此操作)
您可以使用正則表達式來執行此操作,例如:
String code = "<div> style=\"width: 3%\" </div>"
String replaced = code.replaceFirst("width: \\d+", "width: 400")
要提取現有字符串中的值:
Pattern pattern = Pattern.compile("width: (\\d+?)%");
Matcher matcher = pattern.matcher(code);
matcher.find()
matcher.group(1)//Gives 3
最好的方法是使用HTML解析器。 但是,如果您的字符串始終很簡單,則可以使用帶有正則表達式的replaceAll
:
String code = "<div> style=\"width: 3%\" </div>";
String res = code.replaceAll(yourRegex, replacement);
我將為您提供完整的解決方案,但會給您一些提示:
String#replaceAll
\\d+
將匹配數字,因此width:\\s+\\d+
將匹配“ width”,后跟空格,然后是數字 width:\\s+(\\d+)
將捕獲數字的結果(分組) 如果您的字符串是:
String code = "<div> style="width: 3%" </div>"
您可以找到%
存儲的位置,如下所示:
int position = code.indexOf("%");
並假設您將數字存儲在字符串中:
String number = "2";
注意:是2
還是22
或222
都沒有關系。
您可以使用substring
函數獲取總String
:
String totalString = code.substring(0,position - 1) + number + code.substring(position+1, code.length());
現在您可以正常打印了:
System.out.println(totalString);
我希望它將為您服務!
使用String#replaceFirst或String#replaceAll方法: http ://docs.oracle.com/javase/7/docs/api/java/lang/String.html
code = code.replaceFirst("width: ?(.*)%", "width: 400%");
當然可以使正則表達式適應您的要求
您可以使用HTML解析器,例如Jsoup。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.