-1

I want to replace all occurences of the character . in all strings in a solution

These strings look like this:

string sentence = "Hello world. Good bye world";

And I want them all to look like this:

string sentence = "Hello world_ Good bye world";

I want to do it with a regular Expression. I tried with similar approaches as the described here: Regular expression to extract text between square brackets and I read the documentation here https://learn.microsoft.com/en-us/visualstudio/ide/using-regular-expressions-in-visual-studio but I can't figure out how I can continue.

Edit: I am using Visual Studio 2017

Fleve
  • 400
  • 1
  • 5
  • 19

4 Answers4

1
(?<=(?<="|[\.](?<=".*))[^\.]*?)(\.)(?=.*")

It seems that this pattern works in .NET regex because the engine support varable length lookbehind. Demo (click [table] and [context] tab to check replace result )

[Test string]

..string .sentence. = .".Hell.o world.. Good. bye. world.".;.

replace captured character with "_"

..string .sentence. = ."_​Hell_​o world_​_​ Good_​ bye_​ world_​".;. 
  • (\.) : capturing target.(literal period(.))

  • (?=.*") : quote existence after the period being captured.

  • (?<=(?<="|[\.](?<=".*))[^\.]*?) : preceding quote existence and possibly existence of a period with any non-dot characters preceded by a quote before the period being captured

Thm Lee
  • 1,236
  • 1
  • 9
  • 12
0

Visual Studio 2015 Edit/Find and Replace. You will probably find further constraints but should get you started.

In find what:

(string\s[^\s]+\s+=\s+"[^\.]+)(\.)(\s*[^"]+")

In replace with:

$1_$3
Andrew Cowenhoven
  • 2,778
  • 22
  • 27
0

You could do something like the following:

(?<=(?<!\\)"(\"|[^"])*)\.(?=(\"|[^"])*")

...which basically looks for any period preceded by zero or more of any character not a quote or a quote preceded by a backslash, and then preceded by a quote that does not have a leading backslash. That same period is followed by zero or more of any character not a quote or a quote preceded by a backslash, and then followed by a quote not preceded by a backslash.

Keep in mind that this is not foolproof--it does not handle verbatim strings (i.e. @""). You could probably tweak it to accommodate such.

Also, the replacement is just the character you want to change to (i.e. underscore).

Kenneth K.
  • 2,987
  • 1
  • 23
  • 30
-1

A simple expression like:

\.

Should do the trick.

Try using this:

String sentence = "Hello world. Good bye world";
sentence.replaceAll(\\.\g,"_");

Edit: Added global flag to regex.