2015-02-12 95 views
0

我想用同一個單詞的大寫版本替換任何特定單詞的出現。VB.NET - Regex.Replace首字母大寫的句子

代碼:

Dim Sentence As String = "select * from table where field = 1" 
Dim Words As New List(Of String)({"SELECT", "FROM", "UPDATE", "WHERE"}) 

For Each w As String In Words 
    Sentence = Regex.Replace(Sentence, "??", w, RegexOptions.IgnoreCase) 
loop 

你也許能看到我這個去...

Here is reference for Regex.Replace,但我無法弄清楚。

編輯:我只希望替換開始/「字」用空格或斷行或開始/文件的末尾結束。所以像這樣:^m?(word)$m?

+1

因此,只有存儲在一個列表中選擇特定詞? – 2015-02-12 06:18:55

+0

是的,這是正確的。 – CrazyTim 2015-02-17 01:39:01

回答

0

明白了 - 只需使用\b來表示任何空格或換行字符的單詞的兩端:

Dim Sentence As String = "select * from table where field = 1" 
Dim Words As New List(Of String)({"SELECT", "FROM", "UPDATE", "WHERE"}) 

For Each w In Words 
    Sentence = Regex.Replace(Sentence, "\b(" & w & ")\b", w, RegexOptions.IgnoreCase) 
Loop 
1

你可以簡單地用你的話的模式和替代:

For Each w As String In Words 
    Sentence = Regex.Replace(Sentence, w, w, RegexOptions.IgnoreCase) 
Next 

但要注意的是,這並不如取空白或引用文字;所以根據你的實際使用情況,這可能會或可能不適合你。


這裏有一個更高級的正則表達式:

Dim Sentence As String = "select * from table where field = 'fooselectfar foo select foo' " 
Dim Words As New List(Of String)({"SELECT", "FROM", "UPDATE", "WHERE"}) 

For Each w As String In Words 
    Sentence = Regex.Replace(Sentence, "(^|(?<=\W))" & w & "(?=\W)(?=([^']*'[^']*')*[^']*$)", w, RegexOptions.IgnoreCase) 
Next 

Sentence現在SELECT * FROM table WHERE field = 'fooselectfar foo select foo'

+0

嗨懶惰,你知道我怎麼能說/ /之後的空白空白? – CrazyTim 2015-02-17 01:40:17

+0

@CrazyTim看我的更新 – sloth 2015-02-17 07:50:28