Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx to remove hyphens between two strings

Tags:

json

c#

regex

I have a string where I need to replace all hyphens, but only between two delimiters, "clients_field_" and ":"

For example:

"clients_field_4741a6c5-3855-4455-b487-0b38b0038ae6": "[email protected]",
"clients_field_78f225e0-1a78-4930-b251-ad2217baeb1b": "2017-07-26"

When all hyphens are removed it should look like this:

"clients_field_4741a6c538554455b4870b38b0038ae6": "[email protected]",
"clients_field_78f225e01a784930b251ad2217baeb1b": "2017-07-26"

I have tried to find a working regular expression, but I need a little help. I tried the expression (?<=clients_field_)(.*)(?=:), but this will of course select everything between "clients_field_" and ":".

Look at my example

If I can get a few lines of C# code it would be amazing! But I think the RegEx Expression will be just fine! :-)

Thank you!

EDIT: Forgive me! Forgot to mention that the example above is part of a larger json string. So a simple replace with mystring.Replace("-", "") will not work.

EDIT2: Updated my example

like image 200
Jocke Pihlström Avatar asked Aug 08 '17 18:08

Jocke Pihlström


2 Answers

Try this code:

var input = "clients_field_78f225e0-1a78-4930-b251-ad2217baeb1b: 2017-07-26\n"
    + "clients_field_ce1649d3-18e6-48af-a9fb-871c577c7da6: 2018-12-31";
var regex = new Regex("^(?<const>clients_field_)(?<p1>[^:]+)(?<p2>.+)$", RegexOptions.Multiline);
var lines = regex.Matches(input)
    .Cast<Match>()
    .Select(g => $"{g.Groups["const"].Value}{g.Groups["p1"].Value.Replace("-", "")}{g.Groups["p2"].Value}");
var result = string.Join("\n", lines);

result would be

clients_field_78f225e01a784930b251ad2217baeb1b: 2017-07-26 clients_field_ce1649d318e648afa9fb871c577c7da6: 2018-12-31

like image 142
Aleks Andreev Avatar answered Oct 23 '22 03:10

Aleks Andreev


Try a regex based on \G anchor for chaining matches to the desired starting point.

(?<=\G(?!^)|clients_field_)(\w*)-

Replace with what was captured inside the first capturing group.

$1
  • (?<= opens the lookbehind
  • \G(?!^) continues matching on last match but not at ^ start or
  • |clients_field_ match position where the substring is behind
  • (\w*)- capture zero or more word characters followed by -

See this demo at regex101

like image 24
bobble bubble Avatar answered Oct 23 '22 04:10

bobble bubble