[英]Regex get value between braces inclusive the braces with split
我正在嘗試為 Javascript 中的拆分構建一個正則表達式,它將在 {t} 內有帶有文本的大括號的每個位置拆分一個字符串。
我的問題是正則表達式。 目前我有一個與大括號 {} 匹配的正則表達式,但是當我在這些大括號上拆分字符串時,split 函數將刪除大括號。
所以想象我有一個字符串:“我的名字是 {name},我是 {years} 歲”。 在該字符串上,我將使用以下表達式:
const splitted = value.split(/[{}]+/g); // Value is "My name is {name} and I am {years} old"
console.log(splitted);
上面的 console.log 顯示
["My name is ,", "name", " and I am ", "years", " old"]
但我想要
["My name is ,", "{name}", " and I am ", "{years}", " old"]
我究竟做錯了什么?
您可以將此正則表達式與捕獲組一起使用:
const s = "My name is {name} and I am {years} old"; var arr = s.split(/({[^}]*})/g); console.log(arr);
{[^}]*}
匹配以{
開頭並以}
結尾的子字符串,通過在此模式周圍放置一個捕獲組,我們確保該組是split
結果的一部分。
我們可以為此使用惰性量詞。
const s = "My name is {name} and I am {years} old"; var arr = s.split(/({[^]*?})/g); console.log(arr);
惰性量詞*?
為您提供適合正則表達式的最短匹配項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.