[英]Why isn't C# following my regex?
我有一個C#應用程序,該應用程序讀取一個詞文件並查找用<方括號>包裹的詞
當前正在使用以下代碼和所示的正則表達式。
private readonly Regex _regex = new Regex("([<])([^>]*)([>])", RegexOptions.Compiled);
我已經使用了幾個在線測試工具/朋友來驗證正則表達式是否有效,並且我的應用程序證明了這一點(對於那些在家玩的人來說, http://wordfiller.codeplex.com )!
我的問題是,正則表達式也會拾取多余的垃圾。
例如
I'm walking on <sunshine>.
將返回
sunshine>.
它應該返回
<sunshine>
有人知道為什么我的申請拒絕遵守規則嗎?
我認為問題根本不是您的正則表達式。 它可以有所改進-您不需要在每個括號中都使用([])
-但這不會影響結果。 我強烈懷疑問題出在您的C#實現中,而不是您的正則表達式中。
您的正則表達式應將<sunshine>
分為三個獨立的組: <
, sunshine
和>
。 使用下面的代碼對其進行了測試,這就是它的功能。 我的懷疑是,您在C#代碼中的某個位置將第3組附加到第2組,而沒有意識到。 一些快速的C#實驗支持:
private readonly Regex _regex = new Regex("([<])([^>]*)([>])", RegexOptions.Compiled);
private string sunshine()
{
string input = "I'm walking on <sunshine>.";
var match = _regex.Match(input);
var regex2 = new Regex("<[^>]*>", RegexOptions.Compiled); //A slightly simpler version
string result = "";
for (int i = 0; i < match.Groups.Count; i++)
{
result += string.Format("Group {0}: {1}\n", i, match.Groups[i].Value);
}
result += "\nWhat you're getting: " + match.Groups[2].Value + match.Groups[3].Value;
result += "\nWhat you want: " + match.Groups[0].Value + " or " + match.Value;
result += "\nBut you don't need all those brackets and groups: " + regex2.Match(input).Value;
return result;
}
Group 0: <sunshine>
Group 1: <
Group 2: sunshine
Group 3: >
What you're getting: sunshine>
What you want: <sunshine> or <sunshine>
But you don't need all those brackets and groups: <sunshine>
我們將需要查看更多代碼來解決該問題。 您的代碼中某處出現一個錯誤。 該正則表達式不可能返回sunshine>.
。 因此,所討論的正則表達式不是問題。 我會假設,沒有更多細節,就是使索引進入了包含您的匹配項的字符串,並且該字符距離字符串太遠了。
如果只需要<和>之間的文本,那么最好使用:
[<]([^>]*)[>] or simpler: <([^>]+)>
如果要包含<和>,則可以使用:
([<][^>]*[>]) or simpler: (<[^>]+>)
您目前的表情是3個小組賽-用方括號()表示。
如果是<sunshine>,當前將返回以下內容:
第1組:“ <”
第2組:“陽光”
第3組:“>”
因此,如果僅查看第二組,它應該可以工作!
對於觀察到的行為,我只能給出的唯一解釋是,在拔出火柴的地方,是將第2 + 3組而不是第1組加在一起。
您發布的內容效果很好。
Regex _regex = new Regex("([<])([^>]*)([>])", RegexOptions.Compiled);
string test = "I'm walking on <sunshine>.";
var match = _regex.Match(test);
匹配是<sunshine>
我想您需要提供更多代碼。
正則表達式默認是熱切的。 教它偷懶!
我的意思是,*運算符會考慮盡可能多的重復(據說很渴望)。 使用 *? 運算符,而是告訴正則表達式考慮盡可能少的重復(即懶惰):
<.*?>
因為使用的是括號,所以您正在創建匹配組。 這導致match集合與正則表達式創建的組也匹配。 您可以將正則表達式簡化為[<][^>]*[>]
並且僅在您希望的<text>上匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.