简体   繁体   中英

Replace part of string using Regex if this part contains additional spaces

I want to replace all "12-12" to "12:00 AM - 12:00 AM"

For this I've created some logic for replacement :

IDictionary<string, string> Replacements = new Dictionary<string, string>
{
    { "12-12".ToUpperInvariant(), "12:00 AM - 12:00 AM"}
};

Regex AliasReplacementRegex = new Regex(string.Join("|", Replacements.Keys),
    RegexOptions.Compiled | RegexOptions.IgnoreCase);

var input = AliasReplacementRegex.Replace(token, m => Replacements[m.Value.ToUpperInvariant()]);

where token is parameter.

In one of my cases I have input string like "Mo-Th: 12 - 12" How can I match it? It is almost what I expect except additional spaces? Is there any option except adding it to my Regex Rules?


UPD : Is next update correct solution for my case? seems like it is working, but maybe some case which will breal it all.

Regex AliasReplacementRegex = new Regex(string.Join("|", Replacements.Keys),
        RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

You may build a dynamic regex to match any 0+ whitespace symbols around - in your input text, and then implement a custom IEqualityComparer to look up values using "whitespace-insensitive" keys:

public class WhitespaceInsensitiveComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return string.Join("", x.Where(m => !char.IsWhiteSpace(m))) == string.Join("", y.Where(m => !char.IsWhiteSpace(m)));
    }

    public int GetHashCode(string x)
    {
        return string.Join("", x.Where(m => !char.IsWhiteSpace(m))).GetHashCode();
    }
}

and then

var token = "Mo-Th: 12 - 12";
var comparer = new WhitespaceInsensitiveComparer();
var Replacements = new Dictionary<string, string>(comparer);
Replacements.Add("12-12", "12:00 AM - 12:00 AM");
var AliasReplacementRegex = new Regex(string.Join("|", Replacements.Keys.Select(m => 
     Regex.Replace(m, @"\s*-\s*", @"\s*-\s*"))), RegexOptions.IgnoreCase);
var input = AliasReplacementRegex.Replace(token, m => Replacements[m.Value]);

See a C# demo online .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM