VB.NET - Regex.Replace大写单词句子

时间:2015-02-12 06:14:20

标签: regex vb.net

我想用同一个单词的大写版本替换任何特定单词的出现。

代码:

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?

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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