簡體   English   中英

RegExp匹配括在大括號中的單詞

[英]RegExp to match words wrapped in braces

在javascript中,我有一個像這樣的HTML塊:

<h2>{title}</h2>
<p><a href="{url}">{content}</a></p>

我正在嘗試使用正則表達式“匹配”來吐出所有{item}的數組。 所以我的輸出應該是這樣的:

['title', 'url', 'content']

我已經達到了:

var pattern = new RegExp("\{[a-zA-Z]+\}+");
var match = pattern.exec("{Sample} bob {text}");

但它只返回第一個標簽。

這超出了我的正則表達能力。 有人可以幫忙嗎?

干杯!

您需要使用全局標志創建模式:

var pattern = new RegExp("\{[a-zA-Z]+\}", "g");

要么:

var pattern = /\{[a-zA-Z]+\}/g;

然后,您可以在字符串上調用match()方法以獲取匹配列表:

var matches = "{Sample} bob {text}".match(pattern);

我想你想要:

var pattern = new RegExp("\{[a-zA-Z]+\}+", "g");

第二個選項是一個標志,告訴它搜索整個字符串並返回所有匹配項。

有關詳細信息,請參閱: http//www.evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/

就像我喜歡滾動我自己的RegExp(你真的只需要全局標志)一樣,你看過原型模板Trimpath JST還是其他類似的東西?

因為可能滾動你自己不會像上面的例子一樣有效地重復使用。 例如:

String.prototype.template = function (obj) {
 return this.replace(/{([^{}]+)}/g,
  function (full, word) {
   return((typeof obj[word]==='string'||typeof obj[word]==='number')?obj[word]:full);
  }
 );
};

"The {adj1} {adj2} {noun}.".template({adj1: 'lazy',adj2: 'brown', noun: 'dog'})
==> "The lazy brown dog."

這每次運行你的正則表達式,而我相信原型模板基本上只執行一次。

你試過這個嗎?

<script>
var text = '<h2>{title}</h2>\n<p><a href="{url}">{content}</a></p>';
var regex = /\{[a-z]+\}/ig;
var result = text.match(regex);
for (var i = 0; i < result.length; i++) {
    console.debug(i + ". " + result[i]);
}
/*
gives:
0. {title}
1. {test}
2. {url}
3. {content}
*/
</script>

我通過使用exec進行測試而離開了路徑。

暫無
暫無

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

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