java中的replaceAll經常用到,那這里簡單介紹一下其用法,該方法可以使用正則,
使用 ?! 可以忽略大小寫,
簡要例子:
(?i)abc 表示abc都忽略大小寫
a(?i)bc 表示bc忽略大小寫 a((?i)b)c 表示只有b忽略大小寫也可Pattern.compile(rexp,Pattern.CASE_INSENSITIVE)表示整體都忽略大小寫
比如:
public String transform2HtmlTag(String refString){ //pattern: [tagName style = styleValue]text content[/ tagName ] //replace to: <tagName style=/"styleValue/">text content</tagName> //e.g.: text[span style=font-size:14px;color:red;font-family:'arial']123 content[/span] //replace to: text<span style="font-size:14px;color:red;font-family:'arial'">123 content</span> String retValue = ""; if(null != refString && !refString.trim().isEmpty()){ retValue = refString.trim(); retValue = retValue.replaceAll("//[([a-zA-Z][a-zA-Z0-9]*)//s*style//s*=//s*([^//[]*)//]","<$1 style=/"$2/">"); retValue = retValue.replaceAll("//[///s*([a-zA-Z][a-zA-Z0-9]*)//s*//]", "</$1>"); //about handle all XSS security reason, must put this to the end position retValue = retValue.replaceAll("(?i)<(.*)https([^<]*)>", "<$1h-t-t-p-s$2>"); retValue = retValue.replaceAll("(?i)<(.*)http([^<]*)>", "<$1h-t-t-p$2>"); retValue = retValue.replaceAll("(?i)<(.*)ssl2([^<]*)>", "<$1s-s-l-2$2>"); retValue = retValue.replaceAll("(?i)<(.*)ssl([^<]*)>", "<$1s-s-l$2>"); } return retValue;}比如這里例子其中 retValue = retValue.replaceAll("(?i)<(.*)https([^<]*)>", "<$1h-t-t-p-s$2>"); 中https 是不區分大小寫的,那也就是說,Https,httPs,hTtps,HTTPS,https 等不同的大小寫組合都匹配,很方便進行匹配操作,再如:
//replace:[size = sizeValuePX]text[/ size] //to: <span style="font-size:sizeValuePX;">text</span>//attend:px is size unit pixel//eg.: [size = 16px] text000 [/size ] convert to: <span style="16px;">text000</span>retValue = retValue.replaceAll("(?i)//[//s*size//s*=//s*([^//[]*)//]", "<span style=/"font-size:$1;/">");retValue = retValue.replaceAll("(?i)//[///s*size//s*//]", "</span>");其中 size 可以忽略大小寫,也即匹配 Size,siZe,SIZE,size等不同組合,這里可以通過這個正則匹配替換,然后轉換成 html 格式。簡要介紹,記到就寫一下,歡迎拍磚...
|
新聞熱點
疑難解答