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}
4

1 回答 1

1

看起来您只需要在换行符之间进行模式匹配,首先正确地转义它{,然后使用正则表达式文字来解决在字符串中双重转义反斜杠的需要:

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

http://jsfiddle.net/mattball/QNak5

请注意,您甚至不需要{code}s 周围的捕获括号:

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

http://jsfiddle.net/mattball/Jk5cr

于 2013-02-28T22:50:06.117 回答