[英]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"
我想将所有
"12-12"
替换为"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. 其中
token
是参数。
In one of my cases I have input string like "Mo-Th: 12 - 12"
How can I match it? 在我的一种情况下,我输入了
"Mo-Th: 12 - 12"
字符串,我该如何匹配? It is almost what I expect except additional spaces? 除了多余的空格,这几乎是我所期望的? Is there any option except adding it to my Regex Rules?
除了将其添加到我的Regex规则中,还有其他选择吗?
UPD : Is next update correct solution for my case? UPD:下次更新是否适合我的情况? 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: 你可以建立一个动态的正则表达式匹配周围的任何空白0+符号
-
在你输入文字,然后实现自定义的IEqualityComparer使用“空白不敏感”键查找值:
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 . 在线观看C#演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.