Javascript正则表达式拆分与分组

时间:2015-01-16 05:04:17

标签: javascript regex

如果我有以下字符串:

&bull; This is string 1<br />&bull; This is string 2<br />&bull; This is string 3<br />

如何获取&bull;<br />之间的所有内容,以便我最终获得:

["This is string 1", "This is string 2", "This is string 3"]

由于

4 个答案:

答案 0 :(得分:1)

试试这个:

s.replace(/(^&bull;\s*|<br(?: ?\/)?>)/g, "").split(/&bull;\s*/g);

简单但有效,假设字符串始终由“&amp; bull;&lt; br /&gt;”分隔序列。

答案 1 :(得分:0)

您需要使用capturing groups因为js不支持lookbehind断言)。

&bull;\s*(.*?)(?=<br\s*\/>)

(?=<br\s*\/>)肯定前瞻,断言匹配必须跟<br>字符串。 \s*匹配零个或多个空格字符。

DEMO

从组索引1中获取所需的字符串。

> var s = []
undefined
> var f = "&bull; This is string 1<br />&bull; This is string 2<br />&bull; This is string 3<br />"
undefined
> var re = /&bull;\s*(.*?)(?=<br\s*\/>)/g;
undefined
> var m;
undefined
> while ((m = re.exec(f)) != null) {
... s.push(m[1]);
... }
3
> console.log(s)
[ 'This is string 1', 'This is string 2', 'This is string 3' ]

答案 2 :(得分:0)

&bull;\s*(.*?)<br\s*\/>

您只需capturing所需的群组即可。请参阅演示。

https://regex101.com/r/tX2bH4/23

var re = /&bull;\s*(.*?)<br\s*\/>/gi;
var str = '&bull; This is string 1<br />&bull; This is string 2<br />&bull; This is string 3<br />';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
} 

答案 3 :(得分:0)

试试这个:

&#13;
&#13;
var a='&bull; This is string 1<br />&bull; This is string 2<br />&bull; This is string 3<br />';
var r=a.split(/&bull;\s*|<br\s*\/>/);
var nr=r.filter(function(v){return v!==''});
console.log(nr);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;