2013-02-28 64 views
0

考慮:正則表達式,按鍵之間提取文本

This is some text which could have 
line breaks and tabs before and after {code} 
and I want them {code} to be replaced {code}in pairs{code} without any issues. 

我想:

This is some text which could have 
line breaks and tabs before and after <code> 
and I want them </code> to be replaced <code>in pairs</code> without any issues. 

的jsfiddle:http://jsfiddle.net/egrwD/1

簡單的工作文字樣本:

var sample1 = 'test test test {code}foo bar{code} {code}good to know{code}'; 
var regEx1 = new RegExp('(\{code\})(.*?)(\{code\})', 'gi'); 
var r1 = sample1.replace(regEx1, '<code>$2</code>'); 

給出:

test test test <code>foo bar</code> <code>good to know</code> 

非工作示例:

var sample2 = 'test test test {code}\tfoo bar{code} {code}\r\ngood to know{code}'; 
var regEx2 = new RegExp('(\{code\})(.*?)(\{code\})', 'gi'); 
var r2 = sample2.replace(regEx2, '<code>$2</code>'); 

給出:

test test test {code} foo bar{code} {code} 
good to know{code} 

回答

1

看起來LIK Ë你只需要make the pattern match across line breaks,正確逃生,首先{,並用文字正則表達式來解決字符串中需要雙反斜線逃生:你甚至不

/(\{code\})([\s\S]*?)(\{code\})/gi 

http://jsfiddle.net/mattball/QNak5

注需要圍繞{code} S中捕獲括號:

/\{code\}([\s\S]*?)\{code\}/gi 

http://jsfiddle.net/mattball/Jk5cr

+0

ŧ漢克斯!訣竅了。對我來說足夠了。 – Daniel 2013-02-28 23:04:11

+0

不適用於空格:'{code}'。 – yckart 2013-03-18 01:09:20

+0

@yckart,OP中沒有任何內容表明它需要。 – 2013-03-18 01:48:23