簡體   English   中英

正則表達式在括號中查找字符串並替換

[英]regex find string in brackets and replace

我有一個字符串: Hello there [@Some Person](#/path/to/person). How are you? Where is your coffee? [@Another Person](#/path/to/another) said you are not great at regex. Hello there [@Some Person](#/path/to/person). How are you? Where is your coffee? [@Another Person](#/path/to/another) said you are not great at regex.

我想將[@Some Person](#/path/to/person)類的所有模式替換為Some Person

因此,上述示例的最終輸出應為: Hello there Some Person. How are you? Where is your coffee? Another Person said you are not great at regex. Hello there Some Person. How are you? Where is your coffee? Another Person said you are not great at regex.

到目前為止,我有:

> var re = /\[@([\w\s]+)\](\(\S+\))/g
> str.match(re)
> ["[@Some Person](#/path/to/person)", "[@Another Person](#/path/to/another)"]
// matches but not quite what I want.
> str.replace(re, $1)
> "Hello there undefined. How are you? Where is your coffee? undefined said you are not great at regex."
// does not replace as expected.

這是我的正則表達式沙箱 我只想使用str.replace獲得我想要的東西。 不知道是否可能。 似乎應該如此。 請幫忙。

您忘記了$1左右的雙引號:

str.replace(re, "$1")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM