Regex 后视 (JS) 中的可选字符 [英] Optional character in Regex lookbehind (JS)

查看:45
本文介绍了Regex 后视 (JS) 中的可选字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式来解析模板中的一些内容.有开始标签和结束标签,但我只想选择这些标签之间的内容(以便我可以使用 String.replace)

I'm trying to use Regex to parse some content from a template. There are opening tags, and closing tags, but I just want to select the content between these tags (so that I can String.replace)

内容看起来像这样:

OpenTag
  The Content I want
CloseTag

OpenTag The Content I want CloseTag

我使用的正则表达式如下所示:

and the regex I'm using looks like this:

/(?<=OpenTag(\n))(.*?)(?=CloseTag)/msg

我遇到的问题是有时可能会有换行符,有时没有,但是一旦我通过 (\n)? 在后视中将换行符设为可选,换行符被包含在捕获组中(即使它看起来应该是后面的一部分).

The problem I'm having is that sometimes there might be a newline, and other times not, but as soon as I make the newline optional in the lookbehind via (\n)?, the newline gets included in the capture group (even though it seems like it should be part of the look behind).

如果我取消可选的换行符,那么第二个示例的内容将无法匹配.

If I un-optional the newline, then I don't get a match on the second example in content.

regex101.com 上的示例,https://regex101.com/r/teBEQ9/2

Example on regex101.com, https://regex101.com/r/teBEQ9/2

推荐答案

您可以使用以下内容:

OpenTag\s*([^]*?)\s*CloseTag

您想要的文本将在 $1

https://regex101.com/r/FRbTKb/2

这篇关于Regex 后视 (JS) 中的可选字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆