ashwnacharya
ashwnacharya

Reputation: 14871

DO not match regex if it does not occur at the start of the string

I am trying to write a regex for matching a sentence with exactly 3 words with one space between each word, with the middle word being "is".

For example, the regex should be a match if the input is

"This is good"

It should not be a match if the input string is

"This this is good"

This is what I am trying right now:

string text = "this is good";
string queryFormat = @"(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$";
Regex pattern = new Regex(queryFormat, RegexOptions.IgnoreCase);
Match match = pattern.Match(text);

var pronoun = match.Groups["pronoun"].Value; //Should output "this"
var adjective = match.Groups["adjective"].Value; //should output "good"

The above regex matches the string "this this is good"

What am i doing wrong?

Upvotes: 2

Views: 88

Answers (2)

vks
vks

Reputation: 67968

^(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$

Jsut add the ^ start anchor to make it a strict match to 3 words and not a partial match.

^ assert position at start of a line

See demo.

https://regex101.com/r/tX2bH4/18

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174696

You need to add the start of a line anchor ( ^ ).

string queryFormat = @"^(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$";

Upvotes: 2

Related Questions