How to replace characters inside parenthesis using Regex

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sacheverell

    How to replace characters inside parenthesis using Regex

    Alright, I've spent the last few hours trying to figure out Regular Expressions, as they seem suited to what I'm trying to do. ...problem is, I'm not sure how to go about that.

    What I need is an expression that can take a word in a string in parenthesis (for example, "Todd lives on (StreetName) Street.") and replace - in this example, (Streetname) - with user-created input, ideally from an inputbox. It's worth noting that (StreetName) can be anything...(Pos t), (TreeStump) etc.

    So, in summary: A wildcard search (as "(*)"), that then replaces the string in-between the parenthesis with a user-input string.

    I must admit, I'm stumped...RegEx is daunting, to say the least. Of all the things I've learned or tackled in VB.NET, it's the only thing that still leaves me utterly confused. Any ideas?
  • Mariostg
    Contributor
    • Sep 2010
    • 332

    #2
    To search a pattern containing parenthesis, they must be escaped using backslashes. So to search for (Streetname) you must use \(Streetname\).
    If you don't use \, whatever is between () will be retained and available for reference through the variables $1, $2 etc... Exemple, in the sentence "It's worth noting that (StreetName) can be anything...(Pos t), (TreeStump)", $1=StreetName, $2=Post, $3=TreeStump

    You probably don't need regular expressions to do that though. There must be a replace function in vb net.

    Comment

    • Sacheverell

      #3
      Found it

      I was able to do what I wanted with a regex.replace function, using "\(.*\)" as the "parenthesi s with a wildcard in-between" case. It did exactly what I was hoping for, replacing, for example "(StreetNam e)" with "178 Maple", per user input.

      Thanks for the input!

      Comment

      • !NoItAll
        Contributor
        • May 2006
        • 297

        #4
        Go to this site...
        RegExr is an online tool to learn, build, & test Regular Expressions (RegEx / RegExp).

        I've found this to be an essential aid in getting regex syntax correct. It lets you test out your scenarios and build your syntax so you can see the results immediately.

        Comment

        Working...