2016-08-02 45 views
1

我有一些字符串,我想用正則表達式來提取任何html標籤,也是一組大括號中的文本。如何爲以下語句編寫正則表達式?

例如,我可以有以下兩個字符串:

Is this a { <strong> Versioned placeholder </strong> } file? 
Is this a <strong> { Versioned placeholder } </strong> file? 

到目前爲止,我有以下的正則表達式:

(?:\{)(?<PlaceholderValue>\s*[\w\s]*\s*)(?:\}) 

我想是在花中的文本大括號(即「版本化的佔位符」)將放置在PlaceholderValue組中,並且所有其他HTML標記WITHIN中的大括號也將被捕獲。我怎樣才能做到這一點?

請注意,大括號內的html標記是可選的,並不總是存在。如果html標籤不在大括號內,我不感興趣。

+1

什麼是正則表達式的味道? PCRE?見['(?:{|(!!^)\ G)\ s * \ K(<[^>)+> | [^ <>}] + \ b)'demo](https://regex101.com/r/vZ6wK1/1)。 –

+0

是的,PCRE。您的解決方案可以正常工作,但我仍然希望在變量_PlaceholderValue_ – Viqas

+1

中保留值「Versioned placeholder」是不是該化妝品要求?只需在第二個分支周圍添加此組,請參閱https:// regex101。com/r/vZ6wK1/2,甚至['(?:{|(?!^)\ G)\ s * \ K(?:(?<[^>] +>)|(? [^ >}] +)\ b)中'](https://regex101.com/r/vZ6wK1/3)。 –

回答

2

您可以使用

(?:{|(?!^)\G)\s*\K(?:(?<tag><[^>]+>)|(?<PlaceholderValue>[^<}]*[^<}\s])) 

參見regex demo

的模式匹配:

  • (?:{|(?!^)\G) - 先前成功匹配的{或端
  • \s* - 0+空白字符(從左側修整)
  • \K - 匹配重置運算符
  • (?:(?<tag><[^>]+>)|(?<PlaceholderValue>[^<}]*[^<}\s])) - 一組2個備選方案:
    • (?<tag><[^>]+>) - 組 「標籤」 匹配<,1+字符以外<>>
    • | - 或
    • (?<PlaceholderValue>[^<}]*[^<}\s]) - 組 「PlaceholderValue」 捕獲比<}其他0+字符儘可能多,然後是不是空白的必填字符,<}
0
(?<=\{)(.*?)(?= \}) 

這應該取決於什麼正則表達式,你使用

0

你可以在JavaScript嘗試這方面的工作:

var string1 = 'Is this a { <strong> Versioned placeholder </strong> } file?'; 
 
var string2 = 'Is this a <strong> { Versioned placeholder } </strong> file?'; 
 

 
var reg = /<(strong)>[\{\}\w\s]+<\/\1>/; 
 

 
alert(string1.match(reg)[0].replace(/<strong>|<\/strong>|{|}/g, '')); 
 
alert(string2.match(reg)[0].replace(/<strong>|<\/strong>|{|}/g, ''));