2014-09-02 15 views
0

在Ubuntu 12.04上使用Libreoffice 3.5.7.2。在libreoffice calc宏中使用正則表達式從單元格中的括號中提取文本

我在以下格式的計算單元中有文本:(IBM)Ibm Corporation。

我想用正則表達式來提取使用基本宏的()之間的文本。這是我到目前爲止所嘗試的。

Sub getMktValue() 
    Dim oDoc as Object 
    Dim oSheet as Object 
    Dim oCell as Object 

    oDoc = ThisComponent 
    oSheet = oDoc.Sheets.getByName("Income") 
    'regex test code' 
    oCell = oSheet.getCellByPosition(0, 1) 
    stk = oCell.String() 
    myRegex = oCell.createSearchDescriptor 
    myRegex.SearchRegularExpression = True 
    myRegex.SearchString = "\((.*)\)" '"[\([A-Z]\)]" "\(([^)]*)\)" "\(([^)]+)\)"' 
    found = oCell.FindFirst(myRegex) 
    MsgBox found.String 
End Sub 

myRegex.SearchString行包含我嘗試過的各種版本。結果總是一樣的。單元格的全部內容不僅返回()之間的文本。有沒有辦法只提取()之間的文本?

謝謝你,吉姆

回答

1

的.FindFirst發現在電子表格中曾包含SearchString在單元格。如果你想在字符串內搜索,那麼你需要com.sun.star.util.TextSearch。

Sub getMktValue() 
    Dim oDoc as Object 
    Dim oSheet as Object 
    Dim oCell as Object 

    oDoc = ThisComponent 
    oSheet = oDoc.Sheets.getByName("Income") 
    'regex test code' 
    oCell = oSheet.getCellByPosition(0, 1) 
    stk = oCell.getString() 

    oTextSearch = CreateUnoService("com.sun.star.util.TextSearch") 
    oOptions = CreateUnoStruct("com.sun.star.util.SearchOptions") 
    oOptions.algorithmType = com.sun.star.util.SearchAlgorithms.REGEXP 
    oOptions.searchString = "\((.*)\)" 
    oTextSearch.setOptions(oOptions) 
    oFound = oTextSearch.searchForward(stk, 0, Len(stk)) 
    sFound = mid(stk, oFound.startOffset(0) + 1, oFound.endOffset(0) - oFound.startOffset(0)) 
    MsgBox sFound 
    sFound = mid(stk, oFound.startOffset(1) + 1, oFound.endOffset(1) - oFound.startOffset(1)) 
    MsgBox sFound 
End Sub 

問候

阿克塞爾

相關問題