Jump to content

Macros/ScriptForge/SearchRegexInStringQuickwin

From The Document Foundation Wiki


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

All words found that end with "m".
Line and word that ends in "m".

How to run it in BASIC

Create a new document.

  1. Open the Basic IDE
  2. Select the first available blank module
  3. Copy and paste the Basic code
  4. 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

See also