我有一个需要通过正则表达式传递的 html 字符串。此表达式必须检测以下格式的 MailChimp 标签:*|TagName|*
我对正则表达式不太熟悉。我目前使用的是:\*\|([^]]*)\|\*
但是他的正则表达式检测到 2 个匹配项之间的 while 字符串。所以如果我们有:
“带有用户 *|User_Name|* 的示例文本,用于验证带有 *|Date_Value|* 的正则表达式,以及一些其他文本”,
匹配将是:
"*|User_Name|*, to verify regular expression with *|Date_Value|*"
如果有人能告诉我如何更改表达式或使用什么来分别检测所有匹配项。
谢谢
请您参考如下方法:
请试试这个正则表达式:
string source =
"Sample text with user *|User_Name|*, to verify regular expression with *|Date_Value|*, and some other text";
string pattern = @"\*\|.*?\|\*"; // please, notice ".*?" instead of ".*"
// ["*|User_Name|*", "*|Date_Value|*"]
string[] matches = Regex
.Matches(source, pattern)
.OfType<Match>()
.Select(match => match.Value)
.ToArray();
诀窍在于 .*? 而不是 .* - 尽可能匹配几个字母
