简体   繁体   English

JS正则表达式可在regular-expressions.info上使用,但不适用于我的代码

[英]JS regular expression works at regular-expressions.info, but not in my code

I have this string in JavaScript: 我在JavaScript中有以下字符串:

s = "</p><ol><li>First\n</li><li>Second\n</li></ol><p>"

Then I do this (to remove the outer "</p>...<p>"): 然后,我执行此操作(删除外部的“ </ p> ... <p>”):

s = s.replace(/^<\/([^> ]+)[^>]*>(.*)<\1>$/,"$2");

Nothing happens (s is unchanged, and using match() returns false), but if I go try it at http://www.regular-expressions.info/javascriptexample.html , it works! 什么都没发生(s保持不变,并且使用match()返回false),但是如果我去http://www.regular-expressions.info/javascriptexample.html尝试一下,它就可以工作!

I've tried all sorts of things (creating a separate regExp object, using //g, taking out the ^$, replacing [^> ]+ with [a-z0-9]*...) but nothing makes any difference. 我已经尝试了各种方法(创建单独的regExp对象,使用// g,取出^ $,用[a-z0-9] * ...代替[^>] +),但没有任何区别。

It's driving me nuts. 它让我发疯。 can anyone tell me what I'm doing wrong? 谁能告诉我我在做什么错?

The problem is simply that . 问题很简单. does not match newlines \\n . 与换行符\\n不匹配。

If you replace the .* with [\\s\\S]* , your regex should work. 如果将.*替换为[\\s\\S]* ,则您的正则表达式应该可以使用。

[\\s\\S] means match any space or non-space character, which equates to match any character. [\\s\\S]表示匹配任何空格或非空格字符,等同于匹配任何字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM