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.replaceStringactually 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.