RegEx, Match but not include

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
 
G

Gawelek

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

Gawel
 
G

Gawelek

I ma in hurry, sorry

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

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

GAwel
 
M

mikeb

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.
 
M

mikeb

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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Regex Question 1
Rookie thoughts on Regex--useful but not complete 28
Regular Expressions Question 8
c# regex word boundaries 6
Regex - Matching URLS 2
Regular expressions in C# 5
Regex Question 1
need Help Regex 2

Top