英文:
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 = "here is an exmaple```code1```here is an exmaple```code2```here is an exmaple```code3";
console.log(str.match(regex));
<!-- end snippet -->
The output will be
[
"```code1```",
"```code2```",
"```code3"
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论