I have the following string:
"data-template='Test xxx' root{--primary-font:'XYZ Sans';--secondary-font:'Test Sans';--hero-background:#ffbe3f;--header-colour-highlight:#f0591e;--header-background:#ffffff;--header-colour-tabs:#1d2130; }"
I need to replace the spaces from -font:'XYZ Sans'
and -font:'Test Sans'
in order to make it -font:'XYZSans'
and -font:'TestSans'
Edit: the text inside the -font:
may change it is not static.
Could anyone help with that?
CodePudding user response:
Try this:
(?<=XYZ) (?=Sans)|(?<=Test) (?=Sans)
EDIT:
This is another regex pattern will match the value of -front:
and removes any spaces between strings, it is dynamic.
(?<=-font:\s*['\x22][^'\x22] ?)\s(?=[^'\x22]*)
"data-template='Test xxx' root{--primary-font:'XYZ Sans';--secondary-font:'Test Sans';--hero-background:#ffbe3f;--header-colour-highlight:#f0591e;--header-background:#ffffff;--header-colour-tabs:#1d2130; }"
1- (?<=XYZ)
(?=Sans)
match a space proceeded by XYZ
but do not include XYZ
as a part of that match, at the same time the space should be followed by Sans
, but don't include Sans
as a part of the match, we only want the space
. This part will match the first space between XYZ Sans
2- |
the alternation operator |
, it is like Boolean OR
If the first part of the regex(i.e., the pattern before |
) matches a space
, the second part of the regex(i.e., the pattern after |
) will be ignored, this is not what we want because of that we have to add g
modifier which means get all matches and don't return after first match.
3- (?<=Test)
(?=Sans)
match a space proceeded by Test
but do not include Test
as a part of that match, at the same time the space should be followed by Sans
, but don't include Sans
as a part of the match, we only want the space. This part will match the second space between Test Sans
See live demo.
The C# code that does what you want is something like this:
Note: I updated the regex pattern in the code.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string input = "\"data-template='Test xxx' root{--primary-font:'XYZ Sans';--secondary-font:'Test Sans';--hero-background:#ffbe3f;--header-colour-highlight:#f0591e;--header-background:#ffffff;--header-colour-tabs:#1d2130; }\"";
string pattern = @"(?<=-font:\s*['\x22][^'\x22] ?)\s(?=[^'\x22]*)";
string replacement = "";
string result = Regex.Replace(input, pattern, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("\n\n-----------------\n\n");
Console.WriteLine("Replacement String: {0}", result);
}
}