如何匹配被 “` 包围的内容,但结尾的 “` 是可选的?

huangapple go评论59阅读模式
英文:

How to match stuff enclosed by ``` but the ending ``` is optional?

问题

以下是您要翻译的内容:

我现在有这个模式

const pattern = /```([^`]+?)```/gm
const data = "这里有一个示例```代码1```这里有一个示例```代码2```这里有一个示例```代码3```"

它将匹配代码1和代码2,但匹配代码3。换句话说,它将完全封闭的部分匹配。我希望代码3也能匹配。我认为这里重要的一条规则是部分封闭的部分(如代码3)永远不会出现在中间,只会出现在数据流的末尾。

如何做到?

附注:我知道我可以使用这个...

```([^`]+?)```|```([^`]+?)$
英文:

I now have this pattern

const pattern = /```([^`]+?)```/gm
const data = "here is an exmaple```code1```here is an exmaple```code2```here is an exmaple```code3"

It will match code1 and code2 but not code3. In another word it will match perfectly enclosed ones. I want code3 to be matched as well. One rule I think is important here is partially enclosed ones (like code3) will never be in the middle, it will only at the end of the data stream.

How to do it?

P.S. I know that I can use this...

```([^`]+?)```|```([^`]+?)$

答案1

得分: 3

你的要求匹配的一个模式是:

([^`]+)(?:)?/g

以下是代码示例:

const regex = /```([^`]+)(?:```)?/g
const str = "这里是一个示例```代码1```这里是一个示例```代码2```这里是一个示例```代码3```";
console.log(str.match(regex));

输出将会是:

[
  "```代码1```",
  "```代码2```",
  "```代码3"
]
英文:

One pattern that matches your requirements is

/```([^`]+)(?:```)?/g

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const regex = /```([^`]+)(?:```)?/g

const str = &quot;here is an exmaple```code1```here is an exmaple```code2```here is an exmaple```code3&quot;;

console.log(str.match(regex));

<!-- end snippet -->

The output will be

[
  &quot;```code1```&quot;,
  &quot;```code2```&quot;,
  &quot;```code3&quot;
]

huangapple
  • 本文由 发表于 2023年5月26日 10:17:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337270.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定