![](/img/trans.png)
[英]Replace all instances of a pattern with regular expressions in Javascript / jQuery
[英]Find and replace all instances of a pattern in a string using Regular Expressions
使用Excel VBA,我試圖替換看起來像這樣的簡單模式的所有實例:
{some text}
與一些其他常量字符串。 因此,我想查找所有用大括號括起來的文本,並用另一個字符串替換大括號。
我使用以下代碼:
Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "\{.*?\}"
qtext = regEx.Replace(qtext, html_input)
其中qtext
和html_input
是一些字符串。 但這只會替換模式的第一個實例。
例如:
qtext = "yadda yadda {1:NM:=12.000:0.120} omtty doom {1:NM:=6/6} loppy loop"
html_input = "I am HTML"
結果應該是:
"yadda yadda I am HTML omtty doom I am HTML loppy loop"
但是我得到的是:
"yadda yadda I am HTML omtty doom {1:NM:=6/6} loppy loop"
我想念什么?
正如@SJR在他們的評論中所說,您需要將regex對象的Global
屬性設置為True
。 該屬性在MSDN上進行了描述:
全局-一個布爾型屬性,指示是否應針對字符串中所有可能的匹配項測試正則表達式。 默認情況下,全局設置為False。
因此在您的代碼中變為:
Option Explicit
Sub ReplaceText()
Dim regEx As Object
Dim qtext As String
Dim html_input As String
' set up regex
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "\{.*?\}"
regEx.Global = True '<-- set flag to true to replace all occurences of match
' input and replacement text
qtext = "yadda yadda {1:NM:=12.000:0.120} omtty doom {1:NM:=6/6} loppy loop"
html_input = "I am HTML"
' do replace
qtext = regEx.Replace(qtext, html_input)
' test output
MsgBox qtext
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.