简体   繁体   English

如何在C#中通过正则表达式匹配由给定子字符串构造的字符串

[英]how to match a string constructed by given sub strings by regular expression in C#

what should I do to match a string constructed by substrings "CC" "LC" "SW" "RP" "WP" "DT" "LO" "CR" "RC" by regular expression in c#.for example: the input string is "D:(A;;CCLCRPRC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU) (A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)"* and how to match the substring * (A;;CCLCRPRC;;;AU) in it. 我应该怎么做才能用c​​#中的正则表达式匹配由子字符串“ CC”“ LC”“ SW”“ RP”“ WP”“ DT”“ LO”“ ​​CR”“ RC”构造的字符串,例如:输入字符串是“ D:(A ;; CCLCRPRC ;;; AU)(A ;; CCLCRPRC ;;; IU)(A ;; CCLCRPRC ;;; SU)(A ;; CCLCRPWPRC ;;; SY)(A ;; KA; ;; BA)S:(AU; FA; KA ;;; WD)(AU; OIIOFA; GA ;;; WD)“ * 以及如何匹配其中的子字符串* (A ;; CCLCRPRC ;;; AU)

thanks,regards 感谢和问候

You didn't specify anything about the text surrounding the 2 character substrings (the As and the semicolons), so to be flexible, here's a regex that pulls out all strings that are surrounded by brackets, start with anything, end with anything, and contains one or more of the substrings you specified: 您没有为围绕2个字符的子字符串(As和分号)的文本指定任何内容,因此,为了灵活起见,这是一个正则表达式,它可以拉出所有用方括号括起来的字符串,以任何内容开头,以任何内容结尾,以及包含一个或多个您指定的子字符串:

var resultList = new List<string>();
Regex regexObj = new Regex(@"(\(.*?(CC|LC|SW|RP|WP|DT|LO|CR|RC)+.*?\))", RegexOptions.Multiline);
Match matchResult = regexObj.Match(subjectString);
while (matchResult.Success) 
{
    resultList.Add(matchResult.Value);
    matchResult = matchResult.NextMatch();
} 

When run on your example above, the following are extracted: 在上面的示例中运行时,将提取以下内容:

(A;;CCLCRPRC;;;AU)
(A;;CCLCRPRC;;;IU)
(A;;CCLCRPRC;;;SU)
(A;;CCLCRPWPRC;;;SY)

如果要匹配精确的字符串,则只需使用String.IndexOf方法即可。

或者您可以使用String.Contains方法来查找字符串是否为主字符串的一部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM