[英]Regex to get everything between and including curly braces only if a given condition
您好,我正在嘗試創建一個正則表達式,只有當大括號之間的字符串以#開頭並且在右大括號后有一個\n時,它才會抓取大括號之間的所有內容,包括大括號}
我以以下字符串為例-
## 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}
在此示例中,我希望從上面的字符串中提取{#markdown-syntax}
和{#headers}
並將它們替換為空格''
我已經寫了這個正則表達式,但這也抓住了我不想要的{return <h1>Hello, {props.name}
和{2}
。 我只想抓住{#markdown-syntax}
和{#headers}
(包括大括號),因為大括號之間的字符串以#開頭,並且在右大括號之后有一個\n }
將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);
上面使用的正則表達式模式說:
\{ match opening {
# match #
.*? match all content up the first
\} closing }
(?=\n) assert that what follows is a newline character
如果要刪除這些標簽,請使用相同模式的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.