Optional character in Regex lookbehind (JS)

巧了我就是萌 提交于 2020-08-20 12:15:07

问题


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)

The content looks something like this:

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

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.

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


回答1:


You can use something like:

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

And your desired text will be in $1

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




回答2:


The dot in with the s flag matches the \n character as well, and since it's optional it's captured. Use Array.match() and trim the results:

const str = `OpenTag
  The Content I want
CloseTag

OpenTag The Content I want CloseTag`

const result = str.match(/(?<=OpenTag)(.*?)(?=CloseTag)/msg).map(s => s.trim())

console.log(result)


来源:https://stackoverflow.com/questions/58650179/optional-character-in-regex-lookbehind-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!