Vâng, tôi sẽ viết nó như thế này để tránh thực hiện các Regex trận đấu nhiều lần:
match = Regex.Match(input, @"Type1|Type2|Type3");
if (match.Success)
{
// loop, in case you are matching to multiple occurrences within the input.
// However, Regex.Match(string, string) will only match to the first occurrence.
foreach (Capture capture in match.Captures)
{
// if you care to determine which one (Type1, Type2, or Type3) each capture is
switch (capture.Value)
{
case "Type1":
// ...
break;
case "Type2":
// ...
break;
case "Type3":
// ...
break;
}
}
}
Ngoài ra, nếu bạn có một danh sách tùy ý các mẫu mà bạn muốn kiểm tra:
// assumption is that patterns contains a list of valid Regex expressions
match = Regex.Match(input, string.Join("|", patterns));
if (match.Success)
{
// obviously, only one of these return statements is needed
// return the first occurrence
return match.Captures[0].Value;
// return an IEnumerable<string> of the matched patterns
return match.Captures.OfType<Capture>().Select(capture => capture.Value);
}
Đây là một cách tiếp cận khác sử dụng các nhóm chụp được đặt tên để lập chỉ mục từng mẫu. khi tìm thấy một kết quả phù hợp, chúng tôi cố gắng xác định xem nhóm chụp nào đã được so khớp.
Tôi rất không thích mã này do sự nối không cần thiết lặp đi lặp lại của "mẫu" với chỉ số, nhưng tôi không chắc chắn làm thế nào để làm sạch này:
EDIT: Tôi đã dọn dẹp này mã một chút bằng cách sử dụng từ điển
// assumption is that patterns contains a list of valid Regex expressions
int i = 0;
var mapOfGroupNameToPattern = patterns.ToDictionary(pattern => "Pattern" + (i++));
match = Regex.Match(input, string.Join("|", mapOfGroupNameToPattern.Select(x => "(?<" + x.Key + ">" + x.Value + ")")));
if (match.Success)
{
foreach (var pattern in mapOfGroupNameToPattern)
{
if (match.Groups[pattern.Key].Captures.Count > 0)
{
// this is the pattern that was matched
return pattern.Value;
}
}
}
Nguồn
2012-01-13 21:51:05
Đặt regex trong danh sách rồi lặp lại qua danh sách đó cho đến khi bạn nhấn vào một danh sách. – CodesInChaos
'Đặt các regex trong danh sách, và sau đó lặp lại danh sách đó cho đến khi bạn nhấn một .' hoặc viết một regex tốt hơn như' Type1 | Type2 | Type3' –
@LB cách tìm ra phần nào của regex đã thành công khi bạn kết hợp họ? Giả sử các regex là không tầm thường. – CodesInChaos