-1
string sentence = "My current address is #6789, Baker Avenue (CB)".

I would like to replace #6789, Baker Avenue ( with #574, Tomson Street (.

Regular expression would be ^#.*($

How can I do this in C#?

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
HappySnowman
  • 109
  • 1
  • 1
  • 8
  • 4
    `var result = sentence.Replace("#6789, Baker Avenue (","#574, Tomson Street (");` sorted – TheGeneral Aug 23 '18 at 06:30
  • is `string sentence` the only example of what needs to be replaced? or do you have more of those sentences that share a certain pattern? – Mong Zhu Aug 23 '18 at 06:35
  • All the issues are too well-known, see the linked threads that answer and *teach* you how to solve such problems in the future. – Wiktor Stribiżew Aug 23 '18 at 06:53

2 Answers2

2
using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string address = "My current address is #6789, Baker Avenue (CB)";
        Regex regex = new Regex("#.+\\(");
        address = regex.Replace(address, "#574, Tomson Street (");
        Console.WriteLine(address);
    }
}

You need to escape the opening bracket. Also in c# \ character must be escaped, so we need the combination \\( I have removed ^ and $ form your proposal. That characters anchor the pattern to the beginning and end of the phrase. And this is not the case.

mnieto
  • 3,744
  • 4
  • 21
  • 37
  • Kinda unrelated, do you know how to quickly test .net regexp online? http://regexstorm.net/tester seems to never work for me. Giving issues with this pattern too. – Erndob Aug 23 '18 at 06:38
  • 1
    I just have tested on it. Just put `#.*\(` as pattern and `My current address is #6789, Baker Avenue (CB)` as input – mnieto Aug 23 '18 at 06:42
  • @Erndob try this one: https://regex101.com – Mong Zhu Aug 23 '18 at 06:42
1

Try this:

string sentence = "My current address is #6789, Baker Avenue (CB)";

var result = Regex.Replace(sentence, @"#\d+,[^(]+", "#574, Tomson Street ");

The pattern is #\d+,[^(]+.

It's a hash #, followeg by at least one digit \d+, comma, and at least one character which isn't opening bracket: [^(]+

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69