1

Here is the code:

    var x = "Word1 Word2 @aaa|sss Word3 Word4 @aaa|sss Word5";
    var s = Regex.Replace(x, "\\b@aaa|sss\\b", "55", RegexOptions.Singleline);

Expected output:

Word1 Word2 55 Word3 Word4 55 Word5

Actual:

Word1 Word2 @aaa|55 Word3 Word4 @aaa|55 Word5

I am sure, this is something silly... why?

This question is not about "special characters" as in here. This is rather not understanding where the problem is. And the question above doesn't have specific case as in here.

T.S.
  • 18,195
  • 11
  • 58
  • 78
  • 4
    `\b` matches a word boundary, but `@` is not a word character, so the position between the space and the `@` is not a word boundary. Also, you should escape `|` if you want to match a literal pipe rather than alternate – CertainPerformance Feb 28 '19 at 06:49
  • 1
    @CertainPerformance Good catch. I need somehow include this `@` into this search. So... looks like this should do it then: `@"@aaa\|sss\b"` – T.S. Feb 28 '19 at 07:06

3 Answers3

2

Your pattern doesn't work because of two reasons:

  • \b@ won't match a space-at boundary. The space character and the @ character are both non-word characters. There is no word boundary between them, so you can't use word boundary to match that. One alternative is (?<=\s). Another option is (?:(?<=\s)|\b) if you still want to match word boundaries, as well as space-at boundaries.
  • | is not escaped. This means that your regex means "@aaa" or "sss".

Taking these into consideration, you can fix your regex like this:

(?<=\s)@aaa\|sss\b

Demo

Or:

(?:(?<=\s)|\b)@aaa\|sss\b

Demo

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Great! But if I don't really care about whats before `@`. I only care that I have `@aaa\|...` and I only care that whatever comes after `|` is a single word. Hence, I should get away with `@"@aaa\|sss\b"`, correct? For example `my text@aaa|xxxxx. . . . ` should be ok then – T.S. Feb 28 '19 at 07:16
  • 1
    @T.S. Yes that's right. – Sweeper Feb 28 '19 at 07:20
  • Thank you sir! Great to have gurus like yourself – T.S. Feb 28 '19 at 07:26
1

This is actually the correct behavior, as you can test with online regex sites.

This is the Regex string you're searching for: "@aaa\|sss" (you might also need to escape the \).

You need to escape the | symbol as it usually acts as a "or" sign. Also remove the word boundaries, as | cannot be part of a word.

NoConnection
  • 765
  • 7
  • 23
0

Though the above answers work .simple solution for newbies is to esacpe "OR"(|) with \ and use "/gi" to replace All.Here is demo https://regex101.com/r/jdIfsb/1

 var str = "Word1 Word2 @aaa|sss Word3 Word4 @aaa|sss Word5";
     str = str .replace( /@aaa\|sss/gi, "55" )
Anusha kurra
  • 482
  • 3
  • 9
  • I will look at this technique later today. Interesting. Meanwhile, please, vote for reopen this question. Thank you – T.S. Feb 28 '19 at 14:08