简体   繁体   English

正则表达式仅在给定条件下才能获取大括号之间(包括大括号)的所有内容

[英]Regex to get everything between and including curly braces only if a given condition

Hello I am trying to create a regex which will grab everything between and including the curly braces only if the string between braces starts with # and if there is a \n after the closing curly brace }您好,我正在尝试创建一个正则表达式,只有当大括号之间的字符串以#开头并且在大括号后有一个\n时,它才会抓取大括号之间的所有内容,包括大括号}

I have this following string as an example -我以以下字符串为例-

## Markdown Syntax {#markdown-syntax}\n\n (lorem ipsum test).\n\n## Headers {#headers}\n\n function HelloCodeTitle(props) {return <h1>Hello, {props.name}</h1>; } {2}

In this example, I am looking to extract {#markdown-syntax} and {#headers} from the above string and replace them with empty space ''在此示例中,我希望从上面的字符串中提取{#markdown-syntax}{#headers}并将它们替换为空格''

I have written this regex but this is also grabbing {return <h1>Hello, {props.name} and {2} which I do not want.我已经写了这个正则表达式,但这也抓住了我不想要的{return <h1>Hello, {props.name}{2} I am only looking to grab {#markdown-syntax} and {#headers} (including braces) as the string between braces starts with # and there is a \n after the closing curly brace }我只想抓住{#markdown-syntax}{#headers} (包括大括号),因为大括号之间的字符串以#开头,并且在大括号之后有一个\n }

Use match() with the appropriate pattern:match()与适当的模式一起使用:

 var input = "## Markdown Syntax {#markdown-syntax}\n\n (lorem ipsum test).\n\n## Headers {#headers}\n\n function HelloCodeTitle(props) {return <h1>Hello, {props.name}</h1>; } {2}"; var tags = input.match(/\{#.*?\}(?=\n)/g, input); console.log(tags);

The regex pattern used above says to:上面使用的正则表达式模式说:

\{      match opening {
#       match #
.*?     match all content up the first
\}      closing }
(?=\n)  assert that what follows is a newline character

If you want to remove these tags, then use replace with the same pattern:如果要删除这些标签,请使用相同模式的replace

 var input = "## Markdown Syntax {#markdown-syntax}\n\n (lorem ipsum test).\n\n## Headers {#headers}\n\n function HelloCodeTitle(props) {return <h1>Hello, {props.name}</h1>; } {2}"; var output = input.replace(/\s*\{#.*?\}(?=\n)/g, " ").trim(); console.log(output);

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

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