我有一個字符串,其中包含一堆函數調用。我需要提取每次出現的VariableSet函數調用。函數可以以任何順序出現。這裏有一個例子:正則表達式從文本中提取圖案
parsedExpression = "VariableSet(b, 999)If(a = 0,"Black",SetColor(a,b,c))VariableSet("a" ,1.573) VariableSet( c,-2387)"
我需要找到所有以「VariableSet(」上方開始,用它後面的第一個右括號結束,因此,對於例如比賽,我需要一個列表是這樣的:
VariableSet(b, 999)
VariableSet("a" ,1.573)
VariableSet( c,-2387)
我打算用下面的代碼,但我一直沒能確定正確的正則表達式我能想出的最好的是「VariableSet(*(我:?)\ b)」。但它不會產生上述列表。
Dim matches As MatchCollection = Regex.Matches(parsedExpression, "VariableSet\(.*(?i:\)\b)")
' Loop over matches.
For Each m As Match In matches
' Loop over captures.
For Each c As Capture In m.Captures
Dim varName As String = ""
Dim varValue As String = ""
Dim firstCommaPosition As Integer
'For every VariableSet that was found do the following:
'Parse the captured string to get the variable name and value
varName = c.Value.Replace("VariableSet(", "").Replace(")", "")
firstCommaPosition = varName.IndexOf(",")
varValue = varName.Substring(firstCommaPosition + 1)
varName = varName.Substring(0, firstCommaPosition).Replace("""", "")
'Set the variable
ce.Variables(varName) = ce.Evaluate(varValue)
'Remove this instance of VariableSet() function from parsedExpression
parsedExpression = parsedExpression.Replace(c.Value, "")
Next
Next
如果有人能夠提供正確的正則表達式模式,我將不勝感激。
也許這'VariableSet \([^)] * \)' – sln 2014-10-02 16:53:35
哇,我砍了幾個小時,然後用一種只需幾分鐘即可完成的模式回覆!非常感謝! – ESS 2014-10-02 17:15:26