2014-09-24 17 views
2

我試圖通過C#讀取腳本並確定它們是否包含某些單詞,但這些單詞應該是完全相同,而不是僅包含我在尋找的內容。有沒有辦法使用contains-功能,單詞出來,並檢查它是否與確切的單詞相同?我如何用C#的contains函數完全匹配一個單詞?

如何確定它是否包含包含是否與相同搜索條件?

目前我使用下面的腳本:

// GetScriptAssetsOfType<MonoBehaviour>() Returns all monobehaviour scripts as text 
foreach (MonoScript m in GetScriptAssetsOfType<MonoBehaviour>()) 
{ 
    if (m.text.Contains("Material")) 
    { 
     // Identical check? 
    } 
} 
+0

,如果你不希望使用相同運算符,你可以欺騙它,並說m.text.Contains(「材料」)&& m.text.Length == 8 – 2014-09-24 09:52:20

+0

@Miche,但m.text的長度將永遠比8更長。當我試圖單挑這個詞在一個巨大的文本文件中,又名一個腳本。 – 2014-09-24 10:17:24

回答

7

怎麼樣一個正則表達式?

bool contains = Regex.IsMatch(m.text, @"\bMaterial\b"); 
+0

嗯,沒有考慮正則表達式。猜猜我試試看。 – 2014-09-24 09:55:25

0

包含將搜索你把作爲參數 檢查確切的詞作爲本例中的一個小程序

string a = "This is a test"; 
string b = "This is a TEST"; 
Console.WriteLine(a.Contains("test")); 
Console.WriteLine(b.Contains("test")); 

希望我深知另一個檢查中您的問題

+1

是的,在你的測試中這可能工作。但是,如果您的腳本包含colorMaterial這個詞,它仍然會找到材質。讓它不再精確。 – 2014-09-24 09:53:42

0

使用。我希望我能理解你的問題。

// GetScriptAssetsOfType<MonoBehaviour>() Returns all monobehaviour scripts as text 
foreach (MonoScript m in GetScriptAssetsOfType<MonoBehaviour>()) 
{ 
    if (m.text.Contains("Material")) 
    { 
     if(m.text == "Material") 
     { 
      //Do Something 
     } 
    } 
} 
+0

這不會工作。 m.text有時= 1200行。我只希望那個被包含過濾的單個單詞被檢查,如果它等於 – 2014-09-24 09:54:37

+0

你應該使用正則表達式作爲其他答案所說的。如果你不想使用正則表達式的另一個解決方案是拆分單詞,然後在循環中檢查它。你不需要包含tho – VRC 2014-09-24 10:49:46

0

只使用擴展方法,使正則表達式的Handy

擴展類

using System.Text; 
using System.Text.RegularExpressions; 
namespace ConsoleApplication11 
     { 
      public static class Extension 
      { 
       public static Match RegexMatch(this string input, string pattern, RegexOptions regexOptions = RegexOptions.IgnoreCase) 
       { 
        return Regex.Match(input, pattern, regexOptions); 
       } 
      } 
     } 

,並使用上述類的。

 using System.Text; 
     namespace ConsoleApplication11 
     { 
      class Program 
      { 
       static void Main(string[] args) 
       { 
        bool isMatch = "this is text ".RegexMatch(@"\bis\b").Success; 
       } 
      } 
     } 

看到http://www.codeproject.com/Articles/573095/A-Beginners-Tutorial-on-Extension-Methods-Named-Pa

0

所以,你正在尋找一個正則表達式,而不是包含擴展方法,如果不熟悉,現在我明白你的問題

string a = "This is a test for you"; 
string b = "This is a testForYou"; 
string c = "test This is a for you"; 
string d = "for you is this test."; 
string e = "for you is this test, and works?"; 

var regexp = new Regex(@"(\stest[\s,\.])|(^test[\s,\.])"); 


Console.WriteLine(regexp.Match(a).Success); 
Console.WriteLine(regexp.Match(b).Success); 
Console.WriteLine(regexp.Match(c).Success); 
Console.WriteLine(regexp.Match(d).Success); 
Console.WriteLine(regexp.Match(e).Success); 
+0

我不是一個正則表達式專業版,我敢肯定你可以改進這個 – dariogriffo 2014-09-24 10:19:23

相關問題