[.net] Text searching with regular expressions

Started by
5 comments, last by maxest 14 years, 10 months ago
I have some sequence of chars, which looks like this:

abc*******abc*******************abc****...abc
So I have "words" which are separated by the "abc" string. How can I get these words? I've tried regex match like "abc*abc" but it doesn't work.
Advertisement
System.Text.RegularExpressions.Regex.Split(MyInputString, "abc");
----------------------------------------MagosX.com
Wow, thanks a lot :) It works of course... However, I would be really glad if someone could show how to do the same thing using regex pattern
The regular expression would be something like abc(.*?)abc - using . to match any character, * to match any number of them and ? to make the expression un-greedy.

[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]

Yes, that works. Yet only finds the first pattern :(.
For reading all results I use Matches collection and this pattern fills this collection with only the first occurence.
Ah, I see. Assume you had the following input:

abcHELLOabcWORLDabcGOODBYEabc

The first match here is abcHELLOabc, after which the cursor moves past the second abc. The next match after that is abcGOODBYEabc.

I suppose if you wanted to use this method (rather than the more sensible Split) you could do something like this:

Regex Expression = new Regex("abc(.*?)abc"); string Input = "abcHELLOabcWORLDabcTHISabcISabcFUNabc";			int StartPosition = 0;for (; ; ) {	// Try and make a match.	var Match = Expression.Match(Input, StartPosition);	if (!Match.Success) break;	// We made a successful match!	Console.WriteLine(Match.Groups[1].Value);	// Move the start position along manually.	StartPosition = Match.Index + Match.Length - 3;}


Alternatively you could do something like this:

Regex Expression = new Regex("abc(.*?)"); string Input = "abcHELLOabcWORLDabcTHISabcISabcFUNabc";var Matches = Expression.Matches(Input);

...but you'd need to add some error checking to ensure that the original string ended in abc.

[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]

Thanks a lot for this piece of code :)

This topic is closed to new replies.

Advertisement