We help IT Professionals succeed at work.

Extract exact word with a trailing space

Svgmassive
Svgmassive asked
i would like to extract the first Rem that has a space after from the string in regex
 "RemLETS BUILD THE': Rem Room"
in the example Room should be the extracted word
 "Rem LETS BUILD THE': Rem Room"
in the example the entire sentence from LETS BUILD THE': Rem Room"
ignore case false
Comment
Watch Question

Dr. KlahnPrincipal Software Engineer
Depends on what regex engine is in use, but this would be a commonly used form:

Rem\s(.*)

Open in new window


Match "Rem", match a whitespace, and gobble up the rest.
Bill PrewTest your restores, not your backups...
Top Expert 2016
Depending on your comfort level with RegEx, the above posted solution captures the extracted data you want in a "capturing group", so you don't want the full match, you want the first captured group.  Different languages or environments will reference that different ways.

Also, in case you haven't seen it, there is a pretty good online site when you ar developing RegEx expressions.  It lets you create a RegEx to test, and feed it some test data.  It breaks down the RegEx pattern into something a bit more descriptive so you can confirm it's doing what you want, and shows you the result.

Here's an example of your question with the above solution being tested.



»bp
Debug.Print .Replace(ReplaceValue, "")=RemLETS BUILD THE':
 Debug.Print .Replace(ReplaceValue, "$1")=RemLETS BUILD THE': Room
it's not doing it in VBA
Bill PrewTest your restores, not your backups...
Top Expert 2016
So, what exactly are you trying to accomplish.  The question asked to "extract" the text after the first "Rem ", but now it looks like you are trying to replace that?  Can you clarify?

It's a bit more involved in VBA since it doesn't have built in RegEx function, but we can work around that fairly easy using the scripting RegEx object.  But before I post a sample I need to know what you want the result to be.


»bp
Test your restores, not your backups...
Top Expert 2016
Just to give you an idea, here's an example of extracting the full match, and sub match...

Sub Test()
    Dim Matches As Object
    Dim MyText As String
    Dim MyPattern As String

    MyText = "Rem LETS BUILD THE': Rem Room"
    MyPattern = "Rem\s(.*)"

    With CreateObject("Vbscript.Regexp")

        .Global = True
        .IgnoreCase = False
        .Pattern = MyPattern

        If .Test(MyText) Then
            Set Matches = .Execute(MyText)
            If Matches.Count > 0 Then
                Debug.Print "Full match = " & Matches(0)
                Debug.Print "Group match = " & Matches(0).SubMatches(0)
            End If
        End If

    End With

End Sub

Open in new window


»bp
Great this did it also different style "^(.*?)\bRem\b"
thanks
Bill PrewTest your restores, not your backups...
Top Expert 2016
Welcome.


»bp