在 libreoffice calc 宏中使用正则表达式从单元格中的括号中提取文本

Age*_*15x 3 regex macros libreoffice-basic libreoffice-calc

在 Ubuntu 12.04 上使用 Libreoffice 3.5.7.2。

我的计算单元格中的文本格式为:(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
Run Code Online (Sandbox Code Playgroud)

myRegex.SearchString 行包含我尝试过的各种版本。结果总是一样的。返回单元格的全部内容,而不仅仅是 () 之间的文本。有没有办法只提取 () 之间的文本?

谢谢,吉姆

Axe*_*ter 6

您尝试的方法会在(例如电子表格或范围).FindFirst中查找的第一次出现。XSearchableSearchString

如果您想在字符串值内搜索,那么您需要不同的服务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
Run Code Online (Sandbox Code Playgroud)

问候

阿克塞尔