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

标签 regex macros libreoffice-calc libreoffice-basic

在 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

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

谢谢,吉姆

最佳答案

您尝试的方法 .FindFirstXSearchable 中找到(例如电子表格或范围)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

问候

阿克塞尔

关于regex - 在 libreoffice calc 宏中使用正则表达式从单元格中的括号中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25615052/

相关文章:

ruby - 正则表达式匹配多个字符串 - Ruby

macros - LISP:如何跟踪宏

macros - 宏观规则!宏采用字符串文字 "...",扩展为 "..."和 b"..."

macros - OCaml 中的记录字段更新可以推广吗?

if-statement - 我可以在 LibreOffice calc IF 语句中使用 OR 吗?

java - 在 Java 中执行大量字符串替换的最快方法

php - 匹配罗马数字

regex - 使用正则表达式匹配定界符

excel - 为什么逻辑 IFS() 函数总是以小写形式呈现?

python - 在 Excel 列中将文本与 URL 分开