2011-02-09 20 views
0

我想查找下面句子中出現的詞「親愛的」的每個出現的索引。這可以通過RegEx完成嗎?如果是這樣如何?句子中出現的每個詞的索引

你好,親愛的朋友,這是一個字串,包含字親愛的重複;所以親愛的,如果你能告訴我在哪裏,每個親愛位於句子,這將是偉大

+0

這是功課嗎? – 2011-02-09 22:11:54

+0

@Ondrej:不,爲什麼? – imak 2011-02-09 22:18:13

+0

哦,親愛的!...... – 2011-02-09 22:23:50

回答

3

嘗試

foreach(Match m in Regex.Matches(mystring, "dear", RegexOptions.IgnoreCase)) 
{ 
    Debug.Writeline(m.Index); 
} 

這是它開始的角色的索引,如果這就是你的意思。

2

我覺得這是你所需要的:

 string sentence = "Hello DEAR Friend, This is a string that contains repeititons of word dear; so my dear if you can keep count of word dear used, it will be great"; 
     Regex r = new Regex(@"\bdear\b", RegexOptions.IgnoreCase); 
     foreach (Match m in r.Matches(sentence)) 
     { 
      MessageBox.Show(m.Index.ToString()); 
     } 
1

試試這個:

 Regex r = new Regex("dear",RegexOptions.IgnoreCase); 
     string target = "Hello DEAR Friend, This is a string that contains repeititons of word dear; so my dear if you can tell me where each dear is located in the sentence, it will be great"; 
     MatchCollection allMatches = r.Matches(target); 

每個Match對象allMatches將有它相匹配的指數。

1

我不認爲你需要的正則表達式,像我愛他們,這種解決方案很容易:

int index = yourString.IndexOf("dear", StringComparison.OrdinalIgnoreCase); 
while(index > -1) 
{ 
    // Do whatever with the index here 
    index = yourString.IndexOf("dear", index + 1, StringComparison.OrdinalIgnoreCase); 
} 
0

另一個簡單的方法是使用列表理解像這樣:

string1 = "This is the first airplane that flies around the world in far less time than the people thought" 
print [i for i, j in enumerate(string1.split()) if j == 'the'] 

上面的代碼找到所有出現的單詞「the」。 split()函數將句子拆分爲單詞。

相關問題