[Gambas-user] Regular expressions

T Lee Davidson t.lee.davidson at gmail.com
Fri Dec 31 06:59:44 CET 2021


On 12/30/21 17:49, Gianluigi wrote:
> Hi Tobias and Lee,
> 
> I admit that this solution is not very aesthetic, but avoids intervening where it is not needed and this is also compatible with 
> UTF-8:
> 
> Public Sub Main()
> 
>    Dim sLine As String = "The //installation// of a **SSH server on the remote __computer__ is worthwhile in any case!"
>    Dim sItalic, sBold, sUnderline As String
> 
>    Try sItalic = Scan(sLine, "*//*//*")[1]
>    Try sBold = Scan(sLine, "*{**}*{**}*")[1]
>    Try sUnderline = Scan(sLine, "*__*__*")[1]
> 
>    If sItalic Then sLine = Replace(sLine, "//", "<iii>")
>    If sUnderline Then sLine = Replace(sLine, "__", "<uuu>")
>    If sBold Then sLine = Replace(sLine, "**", "<bbb>")
> 
>    Print sLine
> 
> End
> 
> This is definitely more elegant but how to get control over replace when needed?
> 
> Public Sub Main()
> 
>    Dim sLine As String = "The //installation// of a **SSH server on the remote __computer__ is worthwhile in any case!"
> 
>    sLine = RegExp.Replace(sLine, "[_]{2}(.*)[_]{2}", "<uuu>&1<uuu>")
>    sLine = RegExp.Replace(sLine, "[/]{2}(.*)[/]{2}", "<iii>&1<iii>")
>    sLine = RegExp.Replace(sLine, "[*]{2}(.*)[*]{2}", "<bbb>&1<bbb>")
> 
>    Print sLine
> 
> End
> 
> Now I'm going to sleep ;-D
> 
> Good night & Regards
> 
> Gianluigi

Your first solution could make replacements where none should be made. Consider the output if the text is set thusly:
Dim sLine As String = "The //installation// of a __SSH server__ on the remote __computer is worthwhile in any case!"

Hmm, someone made a typo? So all the words from "computer" to the next markup tag will be underlined?

Using regular expressions helps to guarantee that, when markup is replaced, it is done so because there is a matching markup tag 
bracketing the enclosed text.

Now I am unsure what you mean by, "get control over replace when needed." Are you referring to Replace() or RegExp.Replace()?

And, exactly what control do you think might be needed? Are you talking about greedy vs non-greedy (or "frugal" as Tobi puts it)?


-- 
Lee


More information about the User mailing list