How can I make this code more concise

Yusuf 711 Reputation points
2022-10-31T12:58:43.497+00:00

Hi
How can I make this code that using regex more concise, using C# or vb.net

 Imports System  
    Imports System.Text.RegularExpressions  
  
    Public Module Module1  
    Public Sub Main()  
    Dim input As String = "I am 21 year, There are so much people"  
    Dim output As String = ""  
    Dim pattern As String  
  
    pattern = "\bI am (\d+) year\b"  
    For Each match As Match In Regex.Matches(input, pattern)  
        output += Regex.Replace(match.Value, pattern, "I am $1 years old") & Environment.NewLine  
    Next  
  
    pattern = "\bWe met (\d+) years before\b"  
    For Each match As Match In Regex.Matches(input, pattern)  
        output += Regex.Replace(match.Value, pattern, "We met $1 years ago") & Environment.NewLine  
    Next  
  
    pattern = "\b(([\w]+\s+){1,4})so much people\b"  
    For Each match As Match In Regex.Matches(input, pattern)  
        output += Regex.Replace(match.Value, pattern, "$1so many people") & Environment.NewLine  
    Next  

   ' More grammar rules . . .   

    Console.WriteLine(output)  

' Output  
'  =================  
' I am 21 years old  
' There are so many people  

Thanks in advance

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,626 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 27,581 Reputation points Microsoft Vendor
    2022-11-01T08:00:41.257+00:00

    Hi @Yusuf ,
    Since there is no regularity between these substitutions, there seems to be no way to simplify them.
    You can choose to put all the patterns and the strings that replace them in an array and use them later like the code below.

            Dim input As String = "I am 21 year, There are so much people"  
            Dim output As String = ""  
            Dim patterns(2) As String  
            Dim aims(2) As String  
            patterns(0) = "\bI am (\d+) year\b"  
            aims(0) = "I am $1 years old"  
            patterns(1) = "\bWe met (\d+) years before\b"  
            aims(1) = "We met $1 years ago"  
            patterns(2) = "\b(([\w]+\s+){1,4})so much people\b"  
            aims(2) = "$1so many people"  
      
            For i = 0 To patterns.Length - 1  
                For Each match As Match In Regex.Matches(input, patterns(i))  
                    output += Regex.Replace(match.Value, patterns(i), aims(i)) & Environment.NewLine  
                Next  
            Next  
            Console.WriteLine(output)  
    

    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful