C# Regex.IsMatch表达式
Regex.IsMatch的确切表达式是什么C# Regex.IsMatch表达式,c#,regex,C#,Regex,Regex.IsMatch的确切表达式是什么 span[class|align|style] 我试过这个,但没有得到确切的预期结果 if (!Regex.IsMatch(n.Value, @"span\[.*?style.*?\]", RegexOptions.IgnoreCase)) n.Value = Regex.Replace(n.Value, @"(span\[.*?)(\])", "$1" + ValToAdd + "$2"); 我正在检查span是否包含“style”
span[class|align|style]
我试过这个,但没有得到确切的预期结果
if (!Regex.IsMatch(n.Value, @"span\[.*?style.*?\]", RegexOptions.IgnoreCase))
n.Value = Regex.Replace(n.Value, @"(span\[.*?)(\])", "$1" + ValToAdd + "$2");
我正在检查span是否包含“style”元素,如果它存在,则“style”不会与“span”一起插入,反之亦然
有指针吗?您忘了在ValToAdd之前添加
if (!Regex.IsMatch(n.Value, @"span\[.*?\bstyle\b.*?\]", RegexOptions.IgnoreCase))
n.Value = Regex.Replace(n.Value, @"(span\[.*?)\]", "$1|" + ValToAdd + "]");
此外,您的第一个正则表达式将匹配span[class | align | somestyle]
。使用单词边界\b
匹配整个单词。请注意,这仍将匹配span[class | align | some style]
,因为\b
在非单词字符前后匹配。下面的正则表达式将只匹配那些被[|
或|
或|
或|]
包围的样式
@"span\[.*(?<=\||\[)style(?=\||\[).*\]"
<代码> >“SPA\\**(.P>),就像我喜欢正则表达式一样,如果你经常在程序中这样做,你会用一个小类来表示你的令牌做得更好。把这个看作是一个草图:
public class SamToken
{
public string Head { get; set; }
private readonly HashSet<string> properties;
public HashSet<string> Properties{
get{return properties; }
}
public SamToken() : this("") { }
public SamToken(string head)
{
Head = head;
properties = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
public void Add(params string[] newProperties)
{
if ((newProperties == null) || (newProperties.Length == 0))
return;
properties.UnionWith(newProperties);
}
public override string ToString()
{
return String.Format("{0}[{1}]", Head,
String.Join("|", Properties));
}
}
有了这样的功能,可以很容易地添加属性:
SamToken token = SamToken.Parse("span[hello|world]");
token.Add("style", "class");
string s = token.ToString();
正如您所见,我只花了几分钟时间,但您的代码可以更加健壮,更重要的是,可以重用。您不必在每次检查或添加属性时都重写该正则表达式。是否要发布您得到的结果?我已将ValToAdd保留为这样(string ValToAdd=“| style”)@sam you说,我没有得到准确的预期结果
-是否要发布你得到的输出?我正在检查的条件(Regex.IsMatch)就是我在这里所说的预期结果…-span[class | align | style]。span anywhere中的hiphen是否与regex相关?如果您谈论的是使用围绕它们的散乱连字符进行匹配,您可以将regex括在^
和$
之间-它们分别匹配行的开始和结束
SamToken token = SamToken.Parse("span[hello|world]");
token.Add("style", "class");
string s = token.ToString();