Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Enclosing matching text string in parentheses

Last post 03-25-2012, 6:23 PM by Aussie Susan. 1 replies.
Sort Posts: Previous Next
  •  03-23-2012, 1:32 PM 84825

    Enclosing matching text string in parentheses

    Hello Fellow RegExers!

    I have a RE challenge that I have yet to tackle. I'm seeking a Javascript RE that will replace a matched string within parentheses. For example.

    TextStr = "SMITH, JOHN AS TRUSTEE FOR THE JOHNSON FAMILY"

    Desired results would be:

    "SMITH, JOHN (AS TRUSTEE FOR) THE JOHNSON FAMILY"

    I'm using the following RE to match which works fine. It's just the replace that is giving me fits.

    TextStr.match(/\bAS TRUSTEE FOR\b/)

    Any help would be greatly appreciated.

    Gerald 

     

  •  03-25-2012, 6:23 PM 84833 in reply to 84825

    Re: Enclosing matching text string in parentheses

    What regex variant are you using? Regex libraries are not all the same and they provide differing functions and pattern syntax. The following is based on the assumption that your regex will have the necessary functionality.

    EDIT: Sorry - just re-read your posting and I see you mentioned Javascript. I have update the example to the correct syntax and made a note to myself to read more carefully next time!

    There are 2 ways you can do this. The easiest (perhaps) is to look to see if there is a ".replace" function as well as a ".match" function. If so, then something like:

    NewString = TextStr.replace(/\bAS TRUSTEE FOR\b/, "($0)")

    would first locate the text you are after and then replace the whole lot with the same text surrounded by parentheses.

    The second may is to use the information returned by the ".match" function to provide the offset and length of the match and then use the string functions of your language to insert the parentheses yourself.

    If this is the only thing that you are doing using a regex, then you may find it simpler to use the string functions in your programming language to avoid the overhead of the regex engine code.

    Susan

     

View as RSS news feed in XML