【发布时间】:2010-07-22 21:30:09
【问题描述】:
给定以下正则表达式:
\b(MyString|MyString-Dash)\b
还有文字:
字符串 我的字符串 MyString-Dash
对文本运行匹配永远不会找到第二件事(MyString-Dash)的匹配项,因为“-”(破折号)字符不是单词边界字符。以下 javascript 始终将“MyString,MyString”输出到“matches”div(我想将 MyString 和 MyString-Dash 查找为不同的匹配项)。如何定义同时匹配 MyString 和 MyString-Dash 的模式?
<html>
<body>
<h1>Content</h1>
<div id="content">
AString
MyString
MyString-Dash
</div>
<br>
<h1>Matches (expecting MyString,MyString-Dash)</h1>
<div id="matches"></div>
</body>
<script>
var content = document.getElementById('content');
var matchesDiv = document.getElementById('matches');
var pattern = '\\b(MyString|MyString-Dash)\\b';
var matches = content.innerHTML.match(pattern);
matchesDiv.innerHTML = matches;
</script>
</html>
【问题讨论】:
标签: javascript regex