2

This seems like something that should be extremely easy to do but it's not - it's certainly not obvious how to do it, anyway.

I want to write a function in LibreOffice Basic that takes a string, a regexp search pattern, and a replacement string, and returns the string as modified by the regex search & replace. Like a s/search/replace/g in sed or perl.

After several hours trying to make sense of the abysmal documentation, this is what I have:

Function ReSub (T as String, S as String, R as String) As String
   Dim result as String

   ' In other languages, this is trivially easy.  perl has an s/// operator,
   ' and most other languages have a function call. e.g.
   '
   '   perl:   $result = ($T =~ s/$S/$R/g);
   '   python: result = re.sub(S,R,T)

   search = CreateUnoService("com.sun.star.util.TextSearch")
   opts = CreateUnoStruct("com.sun.star.util.SearchOptions")

   opts.algorithmType = com.sun.star.util.SearchAlgorithms.REGEXP

   opts.searchString  = S
   opts.replaceString = R

   search.setOptions(opts)

   found = search.searchForward(T, 0, Len(T))

   ' result = ??????????????
   ReSub = result

End Function

Stepping through this in the IDE shows that this runs OK, but I have no idea where I can get the resulting modified string from. T isn't being modified directly, and it's not in any of the found, search, or opts objects either.

I could write a while loop around search.SearchForware and do the substitution myself using the Mid() statement - but then I'd be restricted to replacing with fixed strings (no back-references or &, unless I implemented them myself. in Basic).

So:

  • does setting opts.replaceString actually DO anything?
  • If so:
    • what does it do?
    • where/how do I retrieve the result of what it does?

Note: this question is about programming in Libre Office Basic to return a changed string, and has nothing at all to do with doing a search & replace on cells with the Libre Office Calc user interface.

cas
  • 671

1 Answers1

2

It sounds like you already have a working solution, so let me simply say that what you are looking for does not seem to exist. With com.sun.star.util.TextSearch, XrayTool shows that neither the search object nor the found result has any methods that perform replacing.

AFAICT, SearchOptions.replaceString is only used for replacing in documents, for example oDoc.replaceAll(oReplace). There is XStringSubstitution but that is only used for PathSubstitution.

So the only way is to do the replacing yourself. Section 19.2 of Andrew's macro document gives a function to replace strings by index.

Personally, I run into this sort of limitation all the time with Basic, so I prefer writing macros in Python-UNO instead. File handling is another thing that is unnecessarily difficult in Basic.

It might be a good idea to add your own answer showing the solution that uses Mid() in case other people find this question. Then probably accept that answer rather than mine.

Jim K
  • 4,439