簡體   English   中英

如果未在字符串開頭出現正則表達式,則不匹配

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

我正在嘗試編寫一個正則表達式來匹配一個句子,該句子正好與3個單詞匹配,每個單詞之間有一個空格,中間單詞是“ is”。

例如,如果輸入為,則正則表達式應為匹配項

"This is good"

如果輸入字符串是

"This this is good"

這是我現在正在嘗試的:

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"

上面的正則表達式匹配字符串“ this this good”

我究竟做錯了什么?

您需要添加行錨的開頭( ^ )。

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添加^起始錨以使其嚴格匹配3個單詞,而不是部分匹配。

^ assert position at start of a line

參見演示。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM