【问题标题】:JavaScript regExp returns "null"JavaScript 正则表达式返回“null”
【发布时间】:2014-06-26 19:44:04
【问题描述】:

我正在制作一个正则表达式来匹配 1 ul 中的所有 li 1 textarea。每次单击按钮时,它都会返回一个值null

这是Fiddle

这是我的function(){...} 的样子:

function doIt() {
    var input = document.getElementById("input");
    var patt = /^<ol>{1}\n+\s?[<li>\w+<\/li>]+\n+<\/ol>{1}$/;
    alert(input.value.match(patt));
} 

我真的不知道为什么patt 不起作用...

这是逻辑(用我自己的话来说):

  • ^ — 起点
  • &lt;ol&gt;{1} — 寻找 1 &lt;ol&gt;
  • \n+ — 查找 1 个或多个新行
  • \s? — 查找 0 个或多个(可选)空格
  • [&lt;li&gt;\w+&lt;\/li&gt;]+ — 查找包含 1 个或多个字符的 1 个或多个 &lt;li&gt;&lt;/li&gt;
  • \n+ — 查找 1 个或多个新行
  • &lt;\/ol&gt;{1} — 寻找 1 &lt;/ol&gt;
  • $ — 终点

  • 我希望 [&lt;li&gt;\w+&lt;\/li&gt;]+ 返回 1 个或多个类似:&lt;li&gt;Hello world :)&lt;/li&gt;

基本上,任何东西都可以在&lt;li&gt;&lt;/li&gt;之间。

【问题讨论】:

  • regExp 不返回 nullmatch 因为没有匹配项而返回
  • @user2864740 This 是免费的
  • 然后使用它——慢慢建立正则表达式。当一个部分不起作用时,分析是分开的。
  • 注意:JavaScript 正则表达式返回的是获得的匹配,而不是分组运算符的结果,所以如果你想获得“1 个或多个类似&lt;li&gt;...&lt;/li&gt;”的东西,那么周围的&lt;ol&gt; 等。不能成为您的正则表达式的一部分。 (如果您想获得一个或多个完整的父有序列表元素作为匹配项,那么您正在采取正确的方法。)
  • 您不应该使用 RegEx 解析 HTML 字符串,尤其是当您已经在浏览器中时。

标签: javascript jquery regex function methods


【解决方案1】:

这是你的模式的实际作用:

^                — Maches the beginning of the string
<ol              — Matches "<ol"
>{1}             — matches ">" one time
\n+              — Matches 1 or more new lines
\s?              — Matches 1 whitespace character (optional)
[<li>\w+<\/li>]+ — Matches any of the characters in "<>A-Za-z_/" 1 or more times
\n+              — Matches 1 or more new lines
<\/ol            — Matches "</ol"
>{1}             — Matches ">" one time
$                — Matches the end of the string

当您匹配字符串的开头和结尾时,模式必须匹配整个字符串,而不是字符串的一部分。

如果你只把这个放在 textarea 中,模式会匹配它:

<ol>
<li>Helloworld</li><li>Hellohowareyou</li><li>good</li>
</ol>

你宁愿想要这样的东西:

var patt = /<ol>\s*(?:<li>[\w !:)]+<\/li>\s*)+<\/ol>/;

解释:

<ol>             — Matches "<ol>"
\s*              — Matches zero or more whitespace characters (including newlines)
(?:              — Starts a non-capturing group
<li>             — Matches "<li>"
[\w+ !:)]+       — Matches any of the characters in "A-Za-z_ !:)" 1 or more times
<\/li>           — Matches "</li>"
\s*              — Matches zero or more whitespace characters
)                — Ends the group
+                — Repeats the group one or more times
\n+              — Matches 1 or more new lines
<\/ol>           — Matches "</ol>"

演示:http://jsfiddle.net/3jthN/2/

【讨论】:

  • 谢谢,效果很好!有没有办法匹配任何字符,而不是将其限制为A-Za-z_ !:)?我试过.*,但它返回null。
  • 啊,我想通了!将[\w+ !:)]+ 替换为.+
【解决方案2】:

方括号表示匹配括号之间的任何单个字符。

您想将&lt;li&gt;&lt;/li&gt; 拉到括号外 - 类似于\&lt;li\&gt;.*\&lt;\\li\&gt;

【讨论】:

  • (OP想要使用分组括号,并完全消除方括号,因此它将匹配“一个或多个”LI组。)
  • @Upperstate 哦,好的。知道为什么它会提示 null 吗?可能是因为表达不正确吧?我知道.* 表示任何字符中的一个或多个,但为什么所有的斜线?
  • 你可能是对的 - 也许所有的斜线都不是必需的。我会摆弄然后更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 2018-03-29
  • 1970-01-01
相关资源
最近更新 更多