Macros/ScriptForge/SearchRegexInStringQuickwin
Appearance
< Macros | ScriptForge
TDF LibreOffice Document Liberation Project Community Blogs Weblate Nextcloud Redmine Ask LibreOffice Donate
How to find all occurrences of a regular expression
Authored by Jean-Pierre Ledure.
The loading of the ScriptForge Basic library can be done elsewhere. In Basic, all used variables are declared explicitly. The concerned code is presented inside a Basic Sub. Run that piece of code and consider the result.
The example searches all words ending with an "m".

How to run it in BASIC
Create a new document.
- Open the Basic IDE
- Select the first available blank module
- Copy and paste the Basic code
- Run Main()
Code
REM How to find all occurrences of a regular expression ?
REM Minimal required version: LibreOffice 7.6
REM Used service(s) String
Sub FindRegex()
Dim sfstr As Object
Dim position as Long
Dim word As String
Dim message As String
Const s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, " _
& "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " _
& "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris " _
& "nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in " _
& "reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. " _
& "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia " _
& "deserunt mollit anim id est laborum."
Const regex = "\b\w+m\b" ' Words ending with "m"
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
sfstr = CreateScriptService("String")
' Init process
message = "Position/Word" & Space(35) & sfstr.sfNEWLINE & sfstr.sfNEWLINE
position = 1
' position is set after each search to the starting position of the found substring or 0.
Do While position > 0 And position < Len(s)
' word contains the found substring
word = sfstr.FindRegex(s, regex, start := position, casesensitive := True) ' position is passed by reference
If position > 0 Then
message = message & position & "/" & word & sfstr.sfNEWLINE
position = position + Len(word)
End If
Loop
MsgBox message, title := "Words ending with ""m"""
End Sub