Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How do I add an option to increment the digit part of a regex by +1.
I have written the below example

What I have tried:

string input="dsfjl kfjd dsfds fds sd abc3, abc4, abc5 dsfdgfdf ggd gdfg dfg  gdfg dfg gdf gf g abc13 abc14 abc20 abc21 abc22 dsfsdf abc13, abc4, abc5";
			Regex rx = new Regex(@"(?:abc(\d+)\s*,?\s*){2,}abc(\d+)");
			foreach (Match m in Regex.Matches(input,rx.ToString())) {
				Console.WriteLine(m.Value);
			}
			Console.ReadKey();

The output generated is
abc3, abc4, abc5
abc13 abc14 abc20 abc21 abc22
abc13, abc4, abc5

But I want to get the output as
abc3, abc4, abc5
abc20 abc21 abc22
i.e. get only the consecutive matches that have the digits incremented by +1
How do I implement that in my code?
Posted
Updated 20-Nov-17 4:49am
Comments
Richard Deeming 20-Nov-17 10:37am    
So why is abc13, abc14 excluded?

Or the second abc4, abc5?
Member 12692000 20-Nov-17 10:41am    
I want 3 or more consecutive strings abcDIGIT separeted by a comma or space where DIGIT is incremented by +1, in case of abc13 abc14 abc20 abc21 abc22, only abc20 abc21 abc22 match the criteria thats why only that part should be taken.
Iqra Ali 20-Nov-17 11:43am    
The question is unclear, there isn't any sequential logic in the question.

Don't.
Regular expressions are string processors, and are excellent at pattern matching - but they don't have any concept of numbers, so the whole idea of "incrementing a counter" does not come at all easy to them - you would have to manually code for each digit and handle overflow, remembering to handle each digit there as well.
Use a regex to capture the the matches, but process the matches in your code to establish the ordering and remove those that don't fit.
 
Share this answer
 
Quote:
How do I do a increment in a regex match?

You don't
Use the RegEx to get a list of all matches, then use a little piece of code to filter/order the list as you want.
*****
Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900