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 格式。
简要介绍,记到就写一下,欢迎拍砖...