在編寫處理字符串的程序或網頁時,常常會有查找符合某些複雜規則的字符串的須要。正則表達式就是用於描述這些規則的工具。換句話說,正則表達式就是記錄文本規則的代碼。合理使用正則表達式確實會爲程序員省去不少字符處理的工做,高速而有效。javascript
正則表達式的語法與使用規範能夠參考http://deerchao.net/tutorials/regex/regex.htmjava
這裏說說用js和java程序處理字符串的一點問題:程序員
<script type="text/javascript"> function check(){ var str = $('#str').val(); str = str.replace(/[\r\n]/g,"");//去掉回車換行 str = str.replace(/[ ]/g,""); //去掉空格 str = str.replace(/\\|\//g,"");//去斜槓 str = str.replace(/"([^"]*)"/g, "「$1」"); //將半角引號轉換全角雙引號 str = str.replace(/"([^']*)"/g, "‘$1’");//將半角引號轉換全角單引號 alert(str); } </script>
用佔位符的方法可處理成對出現的字符,方便快捷。對比用java程序處理相似的字符串能夠這樣寫:正則表達式
package com.test.processstr; public class ProcessString { public static void main(String[] args) { String source = "\"We [are]\" \'family here\',come \\ {on} girl and boy! $$ \n"; String dest = ""; if (source!=null) { dest = source.replaceAll("\\s*|\t|\r|\n|\\\\|,",""); dest = dest.replaceAll(",",","); System.out.println("去掉換行空格斜槓符號後的字符串:" + dest); dest = dest.replaceAll("\"(.*?)\"", "「$1」"); System.out.println("替換英文雙引號符號後的字符串:" + dest); dest = dest.replaceAll("\'(.*?)\'", "‘$1’"); System.out.println("替換英文單引號符號後的字符串:" + dest); dest = dest.replaceAll("\\[(.*?)\\]", "【$1】"); System.out.println("替換中括號符號後的字符串:" + dest); dest = dest.replaceAll("\\{(.*?)\\}", "{$1}"); System.out.print("替換中括號符號後的字符串:" + dest); } } }
也能夠使用util包下的Pattern Matcher 類來實現java的正則表達式處理。工具