In C #, what is the best way to parse this value from a string?

I need to parse the system name from a larger string. The system name is prefixed with "ABC" and then the number. Here are some examples:

ABC500 ABC1100 ABC1300 

the complete line in which I need to parse the system name may look like any of the following elements:

 ABC1100 - 2ppl ABC1300 ABC 1300 ABC-1300 Managers Associates Only (ABC1100 - 2ppl) 

before I saw the latter, I had this code that worked very well:

 string[] trimmedStrings = jobTitle.Split(new char[] { '-', '–' },StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Trim()) .ToArray(); return trimmedStrings[0]; 

but it does not work in the last example, where before ABC there is a bunch of other text.

Can anyone suggest a more elegant and promising way to parse the system name here?

+6
source share
4 answers

One way to do this:

 string[] strings = { "ABC1100 - 2ppl", "ABC1300", "ABC 1300", "ABC-1300", "Managers Associates Only (ABC1100 - 2ppl)" }; var reg = new Regex(@"ABC[\s,-]?[0-9]+"); var systemNames = strings.Select(line => reg.Match(line).Value); systemNames.ToList().ForEach(Console.WriteLine); 

prints:

 ABC1100 ABC1300 ABC 1300 ABC-1300 ABC1100 

demo

+7
source

You can really use Regex and get better results. This should do the trick [A-Za-z]{3}\d+ , and here is Rubular to prove it . Then in the code use it like this:

 var matches = Regex.Match(someInputString, @"[A-Za-z]{3}\d+"); if (matches.Success) { var val = matches.Value; } 
+2
source

You can use regex to parse this. There may be more pronounced expressions, but this works for your case:

 using System; using System.Text.RegularExpressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string txt="ABC500"; string re1="((?:[az][az]+))"; string re2="(\\d+)" Regex r = new Regex(re1+re2,RegexOptions.IgnoreCase|RegexOptions.Singleline); Match m = r.Match(txt); if (m.Success) { String word1=m.Groups[1].ToString(); String int1=m.Groups[2].ToString(); Console.Write("("+word1.ToString()+")"+"("+int1.ToString()+")"+"\n"); } } } } 
+1
source

Regex sure to use Regex for this. Depending on the exact nature of the system name, this may seem sufficient:

Regex systemNameRegex = new Regex(@"ABC[0-9]+");

If part of the ABC name can change, you can change Regex to something like this:

Regex systemNameRegex = new Regex(@"[a-zA-Z]+[0-9]+");

+1
source

Source: https://habr.com/ru/post/945424/


All Articles