You must Sign In to post a response.
  • Category: .NET

    Regex pattern to match terms at the end of the string

    Hi,
    I am working on a windows application and I am using regex to cut off some of the terms from my input text. Some examples of my input text are
    1. AAA Global Services Ltd
    2. Adam Education PLC
    3. ABC Aerolineas SA de CV (Interjet)
    4. Adani Energy Ltd (AEL)

    I am using the following regex pattern:
    ((PLC|Ltd|SA de CV|Holdings))\z

    For 1 and 2, terms Ltd and PLC are getting cut off. But for text like 3 and 4, I want the terms in () also to be cut off along with SA de CV and Ltd. Any help?
    Thanks,
    Bhuvaneswari
  • #764239
    Bhuvaneswari,

    Please try this sample code that will do all sort of things you need with regex

    Namespaces I refered

    using System.Collections.Generic;
    using System.Text.RegularExpressions;


    Actual code

    IDictionary<string, string> map = new Dictionary<string, string>()
    {
    {"Ltd",""},
    {"PLC",""},
    {"SA de CV",""}
    };
    var str = "Given Input"; // Provide your input here
    var regex = new Regex(String.Join("|", map.Keys));
    var oText = Regex.Replace(regex.Replace(str, m => map[m.Value]), @" ?\(.*?\)", string.Empty);
    // oText will have the output

    Please mark this as Answer, if this helps

    Regards,
    Alwyn Duraisingh.M 
    << Database Administrator >>
    Jesus saves! The rest of us better make backups...

  • #764414
    Hi Bhuvaneswari,

    Try this:
    using System.Text.RegularExpressions;

    string szInput = "AAA Global Services Ltd";//... Replace your inputs here
    var myRegEx = new Regex("^(.*)SA|^(.*)PLC|^(.*)Ltd");
    var match = myRegEx.Match(szInput);
    var newInput = match.Success ? (match.Groups[1].Value.Trim() != "" ? match.Groups[1].Value.Trim() : (match.Groups[2].Value.Trim() != "" ? match.Groups[2].Value.Trim() : match.Groups[match.Groups.Count - 1].Value.Trim())) : szInput;
    Console.WriteLine(newInput);

    Hope it helps.
    Regards,
    Shashikant Gurav
    shashikantgurav22@gmail.com


Sign In to post your comments