RegEx, Match but not include

  • Thread starter Thread starter Gawelek
  • Start date Start date
G

Gawelek

Lat say, we have such a string : "Ala ma kota"
Is is possible to express using Regular Expresion, that I want to get
word "kot", that lies behind word "ma" ?
BUT, it is the most important thing, in "matches" I want to get only
word "kot".

Example :

String s = "Ala ma kota";
Regex r = new Regex("match_but_not_include_word_ma\\skota");
MatchesCollection matches = r.Matches(s);

matches[0].ToString() should give ONLY " kota"

I hope it's clear ;)


Gawel
 
I have just figured out,
Regex r = new Regex("match_but_not_include_word_ma\\skota");
Regex r = new Regex("(?=ma)\\skota");

Gawel
 
I ma in hurry, sorry

NOT > Regex r = new Regex("(?=ma)\\skota");

Regex r = new Regex("(?<=ma)\\skota");

GAwel
 
Gawelek said:
Lat say, we have such a string : "Ala ma kota"
Is is possible to express using Regular Expresion, that I want to get
word "kot", that lies behind word "ma" ?
BUT, it is the most important thing, in "matches" I want to get only
word "kot".

Example :

String s = "Ala ma kota";
Regex r = new Regex("match_but_not_include_word_ma\\skota");
MatchesCollection matches = r.Matches(s);

matches[0].ToString() should give ONLY " kota"

No, you can't do that, as matches[0] will always contain what the regex
as a whole matched.

You can come close with a Regex like:

Regex r = new Regex( @"(?:^|\s)ma\s+(\w+)");

which will match the word "ma" (either at the start of the string or
following whitespace) followed by whitespace, and will capture the word
following that whitespace.

You can then get to the captured word directly using:

matches[0].Groups[1];

Test this using:

Console.WriteLine( r.Matches( "Ala ma kota")[0].Groups[1]);

Hope that helps.
 
Gawelek said:
I ma in hurry, sorry

NOT > Regex r = new Regex("(?=ma)\\skota");

Regex r = new Regex("(?<=ma)\\skota");

I stand corrected - I see that the Zero-width assertions participate in
whether or not a regex succeeds, but do not participate in the 'match'
results.

Thanks,
 
Back
Top