Results 1 to 22 of 22

Thread: To get correct result using Regex.Replace or without using Regex.Replace

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    May 2021
    Posts
    172

    To get correct result using Regex.Replace or without using Regex.Replace

    Hello

    I've implemented the Following code to get Space before Capital Letters of Word/String.
    https://www.vbforums.com/showthread.php?239545
    But somehow Spaces were added between the Numeric Values. I thougth of using Regex.Replace to remove spaces but it did not derive Correctly.
    Will indeed appreciate your help either to re-write the code for Function SpacesBeforeCaps or
    help me use correctly the Regex.Replace(...... to get exact result.

    Code:
    Function SpacesBeforeCaps(strIn As String) As String
    
    Dim intI As Integer
            Dim strTemp As String = ""
    
            Do
                intI = intI + 1
                If UCase(Mid(strIn, intI, 1)) = Mid(strIn, intI, 1) Then
                    strTemp = strTemp & " " & Mid(strIn, intI, 1) '.Trim()
                Else
                    strTemp = strTemp & Mid(strIn, intI, 1) '.Trim()
                End If
    
            Loop Until Len(strIn) = intI
            SpacesBeforeCaps = Replace(strTemp, "  ", " ")
     End Function
    
    Private Sub TrialText_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim sentnce As String = "TheBrownFox Quickly Jumped Over the LazyDogs +124567358933765"
            'Output 1
            txtBx4.Text = SpacesBeforeCaps(sentnce)
            'Output 2
            txtBx4.Text = Regex.Replace(txtBx4.Text, "\d+\s", "\d")
    End Sub
    The Output from above coding
    Output 1
    The Brown Fox Quickly Jumped Over the Lazy Dogs + 1 2 4 5 6 7 3 5 8 9 3 3 7 6 5


    Output 2
    The Brown Fox Quickly Jumped Over the Lazy Dogs + \d


    Expected Output
    The Brown Fox Quickly Jumped Over the Lazy Dogs + 124567358933765

    Thanks
    SamD
    162
    Last edited by SamDsouza; Feb 9th, 2024 at 12:16 AM.

  2. #2
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    4,314

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    So, in a Nutshell you want to insert a space in front of a Capital letter and your sequence of digits, if there is no space already?

    Just throw your original String at the Regex-Pattern "([a-z][A-Z])|(\+\d+)".
    https://regex101.com/r/FTyayh/1
    This will return each lowercase letter in your String that CONNECTS to a uppercase Letter as well as the trailing sequence of digits, if it CONNECTS to a "+"-Symbol.
    e.g. "eB" (--> TheBrown...)
    Other Regex-Switches not withstanding (/g /m etc.).
    For your sample string you'd get 4 Matches.
    Be careful with the Matching Groups. Since i used alternation, the sequence of Digits is in Group2 not in Group1 like the lowercase/uppercase combination.

    Then you just loop through the result, check if first Character is "+"-Symbol (then you arrived at the digit-sequence), if no it's a (lowercase) Letter. Optional: Check if first Character is lowercase letter.
    Don't forget to first check if the Group is empty or not (see above because of last match of digit sequence)
    just separate those two with a space
    If it's the "+"-Symbol, separate "+" from everything after it with a space in between
    Done
    Last edited by Zvoni; Feb 9th, 2024 at 02:28 AM.
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ----------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  3. #3
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,030

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    like this perhaps
    Code:
     Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim s As String = "SamD 1 6 2 " & vbNewLine & "The Brown Fox Quickly Jumped Over the Lazy Dogs + 1 2 4 5 6 7 3 5 8 9 3 3 7 6 5 "
            s = Regex.Replace(s, "(?<=\d+)\s+(?=\d+)", "", RegexOptions.Multiline)
            MessageBox.Show(s)
        End Sub
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  4. #4
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,453

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    You realise, the phrase is…

    The Quick Brown Fox Jumps Over the Lazy Dog???

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    May 2021
    Posts
    172

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    Zvoni
    Trying to adapt and implement.

    ChrisE

    s = Regex.Replace(s, "(?<=\d+)\s+(?=\d+)", "", RegexOptions.Multiline)
    using regex101.com got error as + A quantifier inside a lookbehind makes it non-fixed width

    .Paul
    you realise, the phrase isÂ…

    The Quick Brown Fox Jumps Over the Lazy Dog???
    Henceforth Will remember this phrase and will implement for examples of Texts/Strings for posting in the threads.

    Dear All
    Can anything be worked in the code as per #1 for numeric Values ?

    Thanks
    SamD
    163

  6. #6
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,030

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    Quote Originally Posted by SamDsouza View Post
    ChrisE

    using regex101.com got error as + A quantifier inside a lookbehind makes it non-fixed width

    .Paul

    Dear All
    Can anything be worked in the code as per #1 for numeric Values ?

    Thanks
    SamD
    163
    why not just try the code, you can/could have removed the +
    here a Image of the MessageBox the space between the numbers are removed
    Name:  samD.jpg
Views: 101
Size:  25.8 KB

    and to add a space between the Capital letters..
    Code:
     Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim s As String = "SamD 1 6 2 " & vbNewLine & "TheBrown Fox QuicklyJumped Over the Lazy Dogs + 1 2 4 5 6 7 3 5 8 9 3 3 7 6 5 "
            s = Regex.Replace(s, "(?<=\d+)\s+(?=\d+)", "", RegexOptions.Multiline)
            s = Regex.Replace(s, "(?<=[a-z])(?=[A-Z])", " ", RegexOptions.Multiline)
            MessageBox.Show(s)
        End Sub
    on the negative side SamD will change to Sam D
    with a space
    Last edited by ChrisE; Feb 10th, 2024 at 04:24 AM.
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    May 2021
    Posts
    172

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    ChrisE

    Implemented in the Code. Yes It's Working perfectly. Thank you so much
    BTW I've used coding for adding Space before Capital Letters and then implemented the REGEX

    I don't understand why important URL like regex101.com can generate error

    The reason to ask in #5
    Dear All
    Can anything be worked in the code as per #1 for numeric Values ?
    As I wanted to display the "+" and "124567358933765" as "+12" SPACE " 4567358933765
    +12 4567358933765
    I thought of having the Combined code First of adding Space before Capital letters and Adding SPACE inbetween ("+ "with 2 digits And Full LEN of Numbers and then implement REGEX

    on the negative side SamD will change to Sam D
    with a space
    Completely depends on requirements whether Positive side or Negative side

    SamD
    164

  8. #8
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    4,314

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    It wasn’t apparent that you want a space before AND after the first 2 digits
    will be monday

    that said: i still can’t understand why something so simple garnered already 7 posts…
    the most obvious solution would be coded within 10 minutes.
    would it be efficient? Definitely not
    would it get the job done? Hell yes
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ----------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  9. #9
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    4,314

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    It's monday.....

    Without regex and whatnot. Pure parsing.
    Conditions:
    Input-String:
    Arbitrary Input-string that ends with a "+", THAT followed by a Digit-Sequence (A Phone-Number?).
    There is only one single "+"-Symbol in the Input-String.
    After the Digits, there are no more NON-Numeric Characters
    All Characters are ANSI (No Unicode, Chinese, Russian, whatsoever, just English alphabet)

    Output-String:
    Make sure that any Capital Letter is preceded by a SPACE
    Make sure that the "+"-Symbol is preceeded and followed by a SPACE
    Make sure that after the first two Digits (that follow the "+"-Symbol") there is a SPACE
    Make sure that there are NO consecutive SPACES whatsoever

    Algorithm (Untested):
    1) Check for the Position of the "+"-Symbol
    2) Copy/Save everything left from the "+"-Symbol in a Variable "LeftMyInputString" including trimming any whitespace at the start and end
    3) Copy/Save everything right from the "+"-Symbol, including the "+"-Symbol in a Variable "RightMyInputString" including trimming any whitespace at the start and end
    4) Replace (Remove) all SPACES in "RightMyInputString"
    5) In "RightMyInputString" the first Character must be the "+"-Symbol, followed by a sequence of digits.
    6) Insert a SPACE at Position 4 of "RightMyInputString" --> because the first three Characters are "+DigitDigit"
    easy with a (general way to "insert" something")
    RightMyInputString=Left(RightMyInputString,3) & " " & Mid(RightMyInputString,4)

    7) Insert a SPACE at Position 2 of the new RightMyInputString from Step 6

    Now the "Fun" starts
    8) Start For-Loop --> Run through all Capital Letters "A" to "Z"
    9) Replace all found capital Letters with itself, PRECEEDED with a SPACE
    LeftMyInputString=Replace(LeftMyInputString, ACapitalLetter, " " & ACapitalLetter)
    10) End For-Loop
    11) Start Do Until-Loop --> Exit-Condition is at the end of the loop
    12) Replace two consecutive SPACES with a single SPACE in this way:
    tmpString=LeftMyInputString
    LeftMyInputString=Replace(tmpString, " ", " ")
    In VBA it would look like this
    Code:
    Do
      tmpString=LeftMyInputString
      LeftMyInputString=Replace(tmpString, "  ", " ")
    Until LeftMyInputString=tmpString
    13) Exit-Condition: Until LeftMyInputString=tmpString
    14) MyOutputString=LeftMyInputString & " " & RightMyInputString 'We're inserting a SPACE in front of the "+"-Symbol
    15) Done

    Is the algorithm efficient? Definitely not
    Will it get the Job done? Yes
    Can it be optimized? Yes

    Bottom line: To make something efficient, or to optimize something, you MUST have a working solution in the first place to COMPARE against

    And here's the updated Regex
    https://regex101.com/r/FTyayh/3
    It accounts for a maybe already present SPACE between the "+"-Symbol and the digits
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ----------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  10. #10

    Thread Starter
    Addicted Member
    Join Date
    May 2021
    Posts
    172

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    ChrisE

    Code:
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim s As String = "SamD 1 6 2 " & vbNewLine & "TheBrown Fox QuicklyJumped Over the Lazy Dogs + 1 2 4 5 6 7 3 5 8 9 3 3 7 6 5 "
            s = Regex.Replace(s, "(?<=\d+)\s+(?=\d+)", "", RegexOptions.Multiline)
            s = Regex.Replace(s, "(?<=[a-z])(?=[A-Z])", " ", RegexOptions.Multiline)
            s = Regex.Replace(s, "(\d{2,10})", "" & " ", RegexOptions.Multiline) 
            MessageBox.Show(s)
        End Sub
    Tried the above Coloured Line to detect the nos of digits ie 2 numbers with "+" symbol inorder to Get
    +12 4567358933765
    No success because s = Regex.Replace(s, "(\d{2,10})", "" & " ", RegexOptions.Multiline) Can't incorporate Regex pattern for replaced value.


    Zvoni Give me some time to absorb your msg for coding as #9 BTW your result gives as per
    https://regex101.com/r/FTyayh/3
    is + 124567358933765 and not +12 4567358933765 which was asked for in #7

    SamD
    165
    Last edited by SamDsouza; Feb 12th, 2024 at 04:41 AM.

  11. #11
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    4,314

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    Quote Originally Posted by SamDsouza View Post
    ChrisE



    Tried the above Coloured Line to detect the nos of digits ie 2 numbers with "+" symbol inorder to Get
    +12 4567358933765
    No success because s = Regex.Replace(s, "(\d{2,10})", "" & " ", RegexOptions.Multiline) Can't incorporate Regex pattern for replaced value.


    Zvoni Give me some time to absorb your msg for coding as #9 BTW your result gives as per
    https://regex101.com/r/FTyayh/3
    is + 124567358933765 and not +12 4567358933765 which was asked for in #7

    SamD
    165
    The Regex was NOT to return a "ready-to-use" result
    The regex in my link was to return the parts you are interested in.
    The "Replacement" (now look at that word again.....) is your job, not that of Regex

    EDIT: btw: If i read it correctly you don't want a space AFTER the "+"-Symbol"
    In that case skip my Step 7 above
    Last edited by Zvoni; Feb 12th, 2024 at 04:56 AM.
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ----------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  12. #12
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    4,314

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    Quick and dirty in VBA

    Code:
    Sub test()
    Dim InputString As String
    Dim OutputString As String
    Dim LeftInputString As String
    Dim RightInputstring As String
    Dim tmpString As String
    Dim PosOfPlus As Long
    Dim i As Long
        InputString = "TheBrown Fox QuicklyJumped Over the Lazy Dogs + 1 2 4 5 6 7 3 5 8 9 3 3 7 6 5 "
        
        PosOfPlus = InStr(1, InputString, "+")
        LeftInputString = Trim$(Left$(InputString, PosOfPlus - 1))
        RightInputstring = Trim$(Mid$(InputString, PosOfPlus))
            
        RightInputstring = Replace(RightInputstring, " ", "")
        
        If Len(RightInputstring) > 3 Then
            RightInputstring = Left$(RightInputstring, 3) & " " & Mid$(RightInputstring, 4)
        End If
        For i = Asc("A") To Asc("Z")
            LeftInputString = Replace(LeftInputString, Chr(i), " " & Chr(i))
        Next
        Do
            tmpString = LeftInputString
            LeftInputString = Replace(tmpString, "  ", " ")
        Loop Until LeftInputString = tmpString
        OutputString = Trim$(LeftInputString) & " " & Trim$(RightInputstring)
        Debug.Print OutputString
    End Sub
    Output:
    The Brown Fox Quickly Jumped Over the Lazy Dogs +12 4567358933765
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ----------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  13. #13

    Thread Starter
    Addicted Member
    Join Date
    May 2021
    Posts
    172

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    Zvoni
    Quick and dirty in VBA
    Really Hats off to your Speedy response for VBA Coding and checked in MS-Excel VBA. Indeed Wonderful. Perfect Result
    Unfortunately Dirty in VBA because of VBA coding Limitations
    In meantime If you could come up with Regex101 for +12 4567358933765. I've tried enough but no success.

    SamD
    166

  14. #14
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    4,314

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    I'd try something like this
    Code:
    s = Regex.Replace(s, "(\+\d{2})", "$1" & " ", RegexOptions.Multiline)
    EDIT: hmmm...
    just used the code-autogenerator on regex101, but for c#

    Code:
    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
        public static void Main()
        {
            string pattern = @"(\+\d{2})";
            string substitution = @"$1 ";
            string input = @"TheBrownFox Quickly Jumped Over the LazyDogs +124567358933765";
            RegexOptions options = RegexOptions.Multiline;
            
            Regex regex = new Regex(pattern, options);
            string result = regex.Replace(input, substitution);
        }
    }
    Last edited by Zvoni; Feb 12th, 2024 at 06:01 AM.
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ----------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  15. #15

    Thread Starter
    Addicted Member
    Join Date
    May 2021
    Posts
    172

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    Zvoni

    Indeed Superb and Fantastic I'Ve converted VBA to Vb.net and C# to Vb.net

    Thank You All

    Atlast Now more Queries and Trouble for this Thread

    I've changed your VBA to Vb.net
    Code:
    Sub test()
            Dim InputString As String
            Dim OutputString As String
            Dim LeftInputString As String
            Dim RightInputstring As String
            Dim tmpString As String
            Dim PosOfPlus As Long
            Dim i As Long
            InputString = "TheBrown Fox QuicklyJumped Over the Lazy Dogs + 1 2 4 5 6 7 3 5 8 9 3 3 7 6 5 "
    
            PosOfPlus = InStr(1, InputString, "+")
    
            'LeftInputString = Trim$(Left$(InputString, PosOfPlus - 1))
            'RightInputstring = Trim$(Mid$(InputString, PosOfPlus))
    
            LeftInputString = Microsoft.VisualBasic.Strings.Left(InputString, PosOfPlus - 1)
            RightInputstring = Mid(InputString, PosOfPlus).Trim()
    
    
    
            RightInputstring = Replace(RightInputstring, " ", "")
    
            If Len(RightInputstring) > 3 Then
                'RightInputstring = Left$(RightInputstring, 3) & " " & Mid$(RightInputstring, 4)
                RightInputstring = Microsoft.VisualBasic.Strings.Left(RightInputstring, 3) & " " & Mid(RightInputstring, 4)
    
            End If
            For i = Asc("A") To Asc("Z")
                LeftInputString = Replace(LeftInputString, Chr(i), " " & Chr(i))
            Next
            Do
                tmpString = LeftInputString
                LeftInputString = Replace(tmpString, "  ", " ")
            Loop Until LeftInputString = tmpString
            OutputString = Trim$(LeftInputString) & " " & Trim$(RightInputstring)
            'Debug.Print OutputString
            MsgBox(OutputString)
        End Sub
    Your C# converted to vb.net
    Code:
    Public Shared Sub Main()
            Dim pattern As String = "(\+\d{2})"
            Dim substitution As String = "$1 "
            Dim input As String = "TheBrownFox Quickly Jumped Over the LazyDogs +124567358933765"
            Dim options As RegexOptions = RegexOptions.Multiline
            Dim regex As Regex = New Regex(pattern, options)
            Dim result As String = regex.Replace(input, substitution)
            MsgBox(result)
        End Sub
    Ok this is how one replaces in Regex.Repalce

    But what is Role of $1. Had gone through some thread in Stackoverflow which went over my head.

    Thanks

    SamD
    167
    Last edited by SamDsouza; Feb 12th, 2024 at 06:16 AM.

  16. #16
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,453

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    Regex.Replace(s, "(\+\d{2})", "$1" & " ", RegexOptions.Multiline)

    $1 is the highlighted group

  17. #17
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    4,314

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    Think of "$1" as a kind of "variable" regex creates on the Fly to identify the "first" Match-Result

    Quote Originally Posted by .paul. View Post
    Regex.Replace(s, "(\+\d{2})", "$1" & " ", RegexOptions.Multiline)

    $1 is the highlighted group
    Paul, more like
    $1 represents the (first) result/Match-Group, that has been found in "s" USING the highlighted red pattern
    Last edited by Zvoni; Feb 12th, 2024 at 10:00 AM.
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ----------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  18. #18

    Thread Starter
    Addicted Member
    Join Date
    May 2021
    Posts
    172

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    Thanks .Paul and Zvoni for the clarifications.

    Few Questions on

    1. $1 First Match Result, $2 Second Match Result, Can we have more $3, $4 .....etc more Matches result ? Or is it Restricted $1 and $2

    2. What is the Scenario of Regex Pattern that we can combine $1, $2 or do we have to match the pattern individually/Separately
    if Examples could be highlited

    3. Like simple Replace where we try to incorporate .Replace Multiple times
    Code:
    strTxt = Replace(strTxt, "Abcd", "1234").Replace(vbLf, "").Replace(...........
    Can Regex.Replace also be used multiple times like above if yes sample of syntax would be worth

    Thanks
    SamD
    168

  19. #19
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    4,314

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    $1, $2.... $X correlate if you have multiple patterns and specifically multiple "catching groups" in one single Regex

    A Pattern could look like this
    "([a-zA-Z])\s+([0-9])"
    meaning: Look for Text consisting only of letters, if you find some, "store" them in "$1", followed by at least one whitespace, followed by Digits, if you find some "store" the found "number" in "$2"

    ([a-zA-Z]) gets "stored" in "$1"
    ([0-9]) gets "stored" in "$2"
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ----------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  20. #20

    Thread Starter
    Addicted Member
    Join Date
    May 2021
    Posts
    172

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    $1, $2.... $X correlate if you have multiple patterns and specifically multiple "catching groups" in one single Regex

    A Pattern could look like this
    "([a-zA-Z])\s+([0-9])"
    meaning: Look for Text consisting only of letters, if you find some, "store" them in "$1", followed by at least one whitespace, followed by Digits, if you find some "store" the found "number" in "$2"

    ([a-zA-Z]) gets "stored" in "$1"
    ([0-9]) gets "stored" in "$2"
    Ok So Multiple Patterns can be tackled in one single Regex

    What about to reply to point 3
    3. Like simple Replace where we try to incorporate .Replace Multiple times
    Code:
    strTxt = Replace(strTxt, "Abcd", "1234").Replace(vbLf, "").Replace(...........
    Can Regex.Replace also be used multiple times like above if yes sample of syntax would be worth
    SamD
    169

  21. #21
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,030

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    Quote Originally Posted by SamDsouza View Post
    Thanks .Paul and Zvoni for the clarifications.

    Few Questions on

    1. $1 First Match Result, $2 Second Match Result, Can we have more $3, $4 .....etc more Matches result ? Or is it Restricted $1 and $2

    2. What is the Scenario of Regex Pattern that we can combine $1, $2 or do we have to match the pattern individually/Separately
    if Examples could be highlited

    3. Like simple Replace where we try to incorporate .Replace Multiple times
    Code:
    strTxt = Replace(strTxt, "Abcd", "1234").Replace(vbLf, "").Replace(...........
    Can Regex.Replace also be used multiple times like above if yes sample of syntax would be worth

    Thanks
    SamD
    168
    regarding number 3
    you might want to consider the StringBuilder
    here a small example
    Code:
     Public Function cleanString(ByVal s As String) As String
            Dim sb As New StringBuilder(s)
            sb.Replace("1 ", "1") 'remove space from 1
            sb.Replace("2 ", "2") 'remove space from 2
            sb.Replace("3 ", "3") 'remove space from 3
            sb.Replace("4 ", "4") 'remove space from 4
            sb.Replace("Dogs", "Cats") 'you get the idea
            sb.Replace("Lazy", "mouse")
            sb.Replace("Fox ", "Rabbit")
            Return sb.ToString()
        End Function
    
    'usage:
    
     Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
                    Dim SamDString As String = "TheBrown Fox QuicklyJumped Over the LazyDogs + 1 2 3 4 "
    
    
            Dim SB As New System.Text.StringBuilder()
    
            For Each C As Char In SamDString
                If Char.IsUpper(C) Then
                    SB.Append(" "c) 'add space between Captial letters
                End If
                SB.Replace("  ", " ") 'remove any double empty spaces
                SB.Append(C)
            Next C
    
            'look also at:
            'Char.IsDigit(C)
            'Char.IsLetter(C)
            'etc....
           
            TextBox1.Text = Trim(SB.ToString())
    
        End Sub
    
     Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
            TextBox2.Text = cleanString(TextBox1.Text)
        End Sub
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  22. #22
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    4,314

    Re: To get correct result using Regex.Replace or without using Regex.Replace

    regarding 3 (add to ChrisE)
    Think about it:
    1) You execute the first replace
    2) The second replace is executed on the result of the first one.
    3) The third replace is executed on the result of the second one.
    4) and so on...
    It's "cascading"!
    How will your code know, which replace takes precedence, if you try to stuff it into a single replace?
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ----------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width