2017-07-25 36 views
-1

我的字符串如下,我需要在輸出中替換ref的值。從xml字符串中替換字符串的Java正則表達式

Input String: 
<sheet type="xl"><dimension ref="A1:W101"/></sheet> 

Output String: 
<sheet type="xl"><dimension ref="A1:j202"/></sheet> 

我已經嘗試使用該(?< = \ B(REF =))。*(?= />),但它被匹配直到字符串的結尾。

任何人都可以幫助我,我如何使用正則表達式來替換ref值,如輸出字符串。

+1

'*(=/>)' –

+0

使用XML解析器 – ChristofferPass

+0

是輸入參數始終相同嗎? – Lino

回答

1

您可以使用正則表達式是這樣的:

String str = "<sheet type=\"xl\"><dimension ref=\"A1:W101\"/></sheet>"; 
String replaceBy = "A1:j202"; 

str = str.replaceAll("(ref=\")(.*)(\")", "$1" + replaceBy + "$3"); 
System.out.println(str); 

這也將工作:(?<= \ B(REF =))。?

str = str.replaceAll("(?<=\\b(ref=)).*?(?=/>)", "\"" + replaceBy + "\"");