Jump to content
  • Advertisement
Sign in to follow this  
maxest

[.net] Text searching with regular expressions

This topic is 3365 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!