简体   繁体   English

让正则表达式在内容中找到带有换行符的标签内的文本 - JavaScript

[英]Make regex find a text inside tags with line breaks in the content - JavaScript

thanks for coming here, so i've got this little code: 谢谢你来到这里,所以我有这个小代码:

while(/\[del\](.*?)\[\/del\]/i.exec(text) != null)
text = text.replace(/\[del\](.*?)\[\/del\]/i, "<s>$1</s>");

but when there are line breaks, it wont match. 但是当有换行符时,它就不会匹配。 Example: 例:

[del]asdsadasda [删除] asdsadasda
asdadsadsadsadasdsadsa[/del] - this won't be matched asdadsadsadsadasdsadsa [/ del] - 这将不匹配

I'm really new to regex, so what I'm doing wrong? 我对正则表达式真的很新,所以我做错了什么?

By default in many regex flavors, the dot doesn't match the newline character. 默认情况下,在许多正则表达式中,点与换行符不匹配。 Javascript doesn't have the singleline modifier (?s) to change this behaviour. Javascript没有单行修饰符(?s)来改变这种行为。 The most current trick to match all characters including newlines is to use [\\s\\S] that matches all that is a whitespace character and all that is not a whitespace character . 匹配所有字符(包括换行符)的最新技巧是使用匹配所有空白字符的 [\\s\\S] 以及所有不是空白字符的字符

As an aside comment, you don't need to put the replace method in a while loop, since the replace will only perform a replacement if something is found. 作为旁注,您不需要将replace方法放在while循环中,因为replace只会在找到某些内容时执行替换。 If you want to replace all occurences, just add the g command at the end of the pattern. 如果要替换所有出现,只需在模式的末尾添加g命令。

text = text.replace(/\[del\]([\s\S]*?)\[\/del\]/ig, "<s>$1</s>");

Note that for this specific replacement, since your del tag doesn't seem to have parameters, you can simply write: 请注意,对于此特定替换,由于您的del标记似乎没有参数,您可以简单地写:

text = text.replace(/\[(\/?)del\]/ig, "<$1s>");

(it avoids a lot of work) (它避免了很多工作)

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

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