javascript正则表达式由分号拆分,除了&

时间:2016-04-21 09:06:35

标签: javascript regex

我需要&留在字符串中。

示例:

"Rajagiri School of Engineering & Technology;Indian School of Mines University;"

输出应为:

['Rajagiri School of Engineering & Technology', 'Indian School of Mines University']

2 个答案:

答案 0 :(得分:1)

如果您想匹配"真实; s"以外的所有内容:

(?:&|[^;])+

会奏效。或(?:&\w+;|[^;])+,如果不仅仅需要&个实体。

如果你的正则表达式引擎支持拆分操作,也许这个正则表达式(只有在&amp之前没有匹配的分号)也是个好主意

(?<!&amp);

如果您的正则表达式实现支持lookbehind assertions内的无限重复,也可以使用上面的其他实体(?<!&\w+);。但是,大多数人都不会将.NET作为例外。

在Javascript中:

var data = "Rajagiri School of Engineering &amp; Technology;Indian School of Mines University;"
var regex = "(?<!&amp);";
var result = data.split(regex);
console.log(result);

&#13;
&#13;
<p id="demo">Click the button to change the text in this paragraph.</p>
<button onclick="myFunction()">Try it</button>

<script>
  function myFunction() {
    var data = "Rajagiri School of Engineering &amp; Technology;Indian School of Mines University;"
    var regex = "(?<!&amp);";
    var result = data.split(regex);
    document.getElementById("demo").innerHTML = result;
  }
</script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用replace进行回调,并在&amp之前放弃;的结果。

var str = "Rajagiri School of Engineering &amp; Technology;Indian School of Mines University;";

var arr = str.replace(/(&amp)?;/g, function($0, $1) { return $1=="&amp"? $1+";" : "\n";
          }).split("\n").filter(Boolean);

<强>输出:

["Rajagiri School of Engineering &amp; Technology",
 "Indian School of Mines University"]