2014-10-04 72 views
0

我需要替換一些字符,但只能在括號內。因此,假設以下示例如何在替換內使用vba正則表達式替換

this is a string (with comment), this is another string without comment, and this is a string (with one comment, and another one) 

我需要能夠根據逗號值分割這個句子。除了令人討厭的事實,最後的評論還包含一個逗號,這樣可以很好地解決問題,所以我的分裂有點有限。期望的結果必須是如下

this is a string (with comment), 
this is another string without comment, 
and this is a string (with one comment, and another one) 

我使用VBA訪問,我的方法是首先分離所有的評論(括號中的內容),具有不同的字符替換逗號(說管符號),並使用拆分或替換選項來拆分整個句子。

我試過的東西如下,但我沒有像我喜歡的那樣處理正則表達式匹配。任何選擇,或對我如何最好地解決它的見解?

Function commentFixer(s As String, t As String) As String 

't = token to be replaced, eg a comma 

Dim regEx As New RegExp 
Dim match As String 
regEx.Global = True 
p = "(\([^()]*\)*)" 
'match all commented substrings 
regEx.Pattern = p 

'below obviously doesn't work, as the match itself is not accepted as a character. Any way to deal with this ? 

match = "$1" 'How can I store this in a variable to perform a replacement on the result ? 
dim r as string 'replacement value 

r = Replace(match, t, "|") 

commentFixer = regEx.Replace(s, r) 

End Function 

Sub TestMe() 

s = commentFixer("this is a string (with comment), this is another string without comment, and this is a string (with one comment, and another one)", ",") 
Debug.Print s 

'expected result : this is a string (with comment), this is another string without comment, and this is a string (with one comment| and another one) 
End Sub 

回答

0

在這裏你去,

(.*?,)\s*(?![^()]*\))|(.+)$ 

組指標1和2包含所需的字符串。

DEMO

+0

感謝拉吉,不幸的是,這並不在VBA內(TBH我guees,而不是一個真正的專家)的工作,因爲它不喜歡沒有實際內容的匹配。 Regex.split在VBA中不受支持,這使得它更復雜 – Wokoman 2014-10-04 12:56:25

+0

請參閱http://regex101.com/r/aP7aD5/3 – 2014-10-04 13:03:32