本文整理汇总了C#中Regex.Execute方法的典型用法代码示例。如果您正苦于以下问题:C# Regex.Execute方法的具体用法?C# Regex.Execute怎么用?C# Regex.Execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Regex
的用法示例。
在下文中一共展示了Regex.Execute方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Matches
/****************************************
* Matches
*
* returns starting index of match or -1
*/
public int Matches(string subject, string regex, RegexOption option = DefaultOption)
{
var r = new Regex(regex, option);
var match = r.Execute(subject);
if (match.Success)
return match.Groups[0].Start;
return -1;
}
示例2: Matching
/****************************************
* Matching
*
* returns matching substring if found, null if not or if group index is out of range (group 0 is entire match, 1 is first group etc.)
*/
public string Matching(string subject, string regex, RegexOption option = DefaultOption, int group = 0)
{
var r = new Regex(regex, option);
var match = r.Execute(subject);
if (match.Success && match.Groups.Count > group)
return match.Groups[group].Value;
return null;
}
示例3: Substitute
/****************************************
* Substitute
*
* Replaces all occurrences of regex with replacement string
*/
public string Substitute(string subject, string regex, string replace, RegexOption option = DefaultOption, int offset = 0)
{
// Special cases, if $N is passed then use the substring as the replacement
// if #N is passed then use substring, pad with a space on either side
var group = -1;
var substituteGroup = replace.Length == 2 && (replace[0] == '$' || replace[0] == '#') &&
int.TryParse(replace[1].ToString(), out group);
var pad = !substituteGroup ? false : replace[0] == '#';
var r = new Regex(regex, option);
var match = r.Execute(subject);
var replacements = new List<Replacement>();
while (match.Success)
{
if (match.Groups[0].Start >= offset)
{
var doReplace = false;
if (substituteGroup)
{
if (match.Groups.Count > group)
{
doReplace = true;
replace = string.Format("{0}{1}{0}", pad ? " " : "", match.Groups[group].Value);
}
}
else
{
doReplace = true;
}
if (doReplace)
{
replacements.Add(new Replacement
{
Start = match.Groups[0].Start,
Length = match.Groups[0].Length,
Value = replace
});
}
}
match = match.NextMatch;
}
replacements.Reverse();
foreach (var replacement in replacements)
{
subject = subject.Remove(replacement.Start, replacement.Length);
subject = subject.Insert(replacement.Start, replacement.Value);
}
return subject;
}