Using regex to capture a numeric value in a string in C #

I have a character string that contains 0 or more occurrences of ABC = dddd inside it. dddd means an integer value, not necessarily four digits.

What I would like to do is to capture the integer values โ€‹โ€‹that occur in this template. I know how to match regular expressions, but I'm new to capture. You do not need to write all the integer values โ€‹โ€‹of ABC in one call - this is great to iterate over a string.

If this is too complicated, I will just write a tiny parser, but I would like to use a regex if it's elegant enough. The expertise was highly appreciated.

+4
source share
2 answers

First we need to start with a regular expression that matches the pattern we are looking for. This will be consistent with your example (if ABC is alphanumeric): \w+\s*=\s*\d+

Next, we need to determine what we want to fix in the match by defining capture groups .. Net includes support for the named capture groups, which I absolutely adore. We specify a group with (?<name for capture>expression) , turning our regular expression into: (?<key>\w+)\s*=\s*(?<value>\d+) . This gives us two captures, key and value.

Using this, we can iterate over all matches in your text:

 Regex pattern = new Regex(@"(?<key>\w+)\s*=\s*(?<value>\d+)"); string body = "This is your text here. value = 1234"; foreach (Match match in pattern.Matches(body)) { Console.WriteLine("Found key {0} with value {1}", match.Groups.Item["key"].Value, match.Groups.Item["value"].Value ); } 
+3
source

You can use something like this:

 MatchCollection allMatchResults = null; try { // This matches a literal '=' and then any number of digits following Regex regexObj = new Regex(@"=(\d+)"); allMatchResults = regexObj.Matches(subjectString); if (allMatchResults.Count > 0) { // Access individual matches using allMatchResults.Item[] } else { // Match attempt failed } } catch (ArgumentException ex) { // Syntax error in the regular expression } 

Based on your computer, maybe this is more than what you need:

 try { Regex regexObj = new Regex(@"=(\d+)"); Match matchResults = regexObj.Match(subjectString); while (matchResults.Success) { for (int i = 1; i < matchResults.Groups.Count; i++) { Group groupObj = matchResults.Groups[i]; if (groupObj.Success) { // matched text: groupObj.Value // match start: groupObj.Index // match length: groupObj.Length } } matchResults = matchResults.NextMatch(); } } catch (ArgumentException ex) { // Syntax error in the regular expression } 
+1
source

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


All Articles