試試這個:
var str:String = "I don't recall saying ' pick up the boot ' or ' now is the time ' . But it's possible , so I may have .";
// "foo ' bar ' baz" => "foo 'bar' baz"
var re1:RegExp = /'\s(.*?)\s'/g;
str = str.replace(re1, "'$1'");
// "foo , bar . baz" => "foo, bar. baz"
var re2:RegExp = /\s([.,])/g;
str = str.replace(re2, "$1");
對於這個特定字符串,你會得到結果:
I don't recall saying 'pick up the boot' or 'now is the time'. But it's possible, so I may have.
可能是第一個正則表達式需要進行一些調整,因爲它不會像
字符串工作
I didn ' t say ' foo '.
,因爲它會被轉換爲
I didn 't say' foo '.
在第一正則表達式中使用的特殊符號簡短說明:
\s
爲空格字符(空格,製表符)
.
指任何字符
*
零個或多個重複
?
使得*
量詞非貪婪,所以它會匹配儘可能少的字符
- 將其全部包裝在括號中創建捕獲組;我們可以稍後在替換字符串是指其內容
$1
你可以找到關於this site或從Adobe的文檔的this section關於正則表達式的更多信息。
謝謝!你會如何用英文寫出第一個re1?它會是:re1是一種模式,它會發現單引號後跟...?我最難以理解的部分是(。*?)另外在替換中,''$ 1''在做什麼? – David 2012-01-03 19:56:52
我添加了簡短的解釋,但是如果您要在代碼中使用regexp,最好閱讀一下它們。 – 2012-01-03 20:10:25
是的,他們一直在閱讀,但你的解釋使得速度更快。再次感謝。 – David 2012-01-03 20:32:10