Java中的replaceAll用法__Java

來源:互聯網
上載者:User

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 positionretValue = 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 格式。


簡要介紹,記到就寫一下,歡迎拍磚...






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.