簡體   English   中英

使用正則表達式檢測特殊字符串並僅替換其中一部分

[英]Using regex detect special string and replace only a part of it

我對這個問題的措辭有些困難,所以我找不到答案。 另外,可能沒有簡單的方法可以執行我要執行的操作。

我正在嘗試檢測一個特殊的序列,在我的情況下是a ; 后面跟一個數字,並替換; &#后跟相同的數字。 例如:

;123;;234; ;345; --> {ê ř

正則表達式可以輕松找到我的序列,但是如何保留要替換的數字?

當然,對每個數字使用單獨的replace將起作用,但是我正在尋找比這更優雅的東西:

str = str.replace(";1","&#1");
str = str.replace(";2","&#2");
...
str = str.replace(";9","&#9");

謝謝!

也許是這樣,未經測試。 檢查Javadoc:

str = str.replaceAll( ";(\\d+)", "&#$1;" );

換句話說,您要替換; 僅在&#之后緊跟數字。 在這種情況下,您可以使用類似的先行機制

str = str.replaceAll(";(?=\\d)","&#");

;(?=\\\\d)含義與我之前所述的完全一樣:accept ; 僅在其后有\\\\d時,但不要在匹配項中包括該\\\\d ,因此僅; 部分將被替換。

這是您需要的正則表達式

String s =";123;;234; ;345;";  
Pattern p = Pattern.compile(";(\\d)");
Matcher m = p.matcher(s);
while (m.find()){
  s= s.replace(";"+m.group(1), "&#"+m.group(1));    
}
System.out.println(s);

暫無
暫無

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

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