[英]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". 我正在尝试编写一个正则表达式来匹配一个句子,该句子正好与3个单词匹配,每个单词之间有一个空格,中间单词是“ 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" 上面的正则表达式匹配字符串“ this this good”
What am i doing wrong? 我究竟做错了什么?
您需要添加行锚的开头( ^
)。
string queryFormat = @"^(?<pronoun>[A-Za-z0-9]+) is (?<adjective>[A-Za-z0-9]+)$";
^(?<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. Jsut添加
^
起始锚以使其严格匹配3个单词,而不是部分匹配。
^ assert position at start of a line
See demo. 参见演示。
https://regex101.com/r/tX2bH4/18 https://regex101.com/r/tX2bH4/18
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.