我有一组句子需要替换,例如:
abc => cde
ab df => de
...
我有一条文本可以在哪里进行更改。
但是我没有办法事先知道上述文本的情况。
因此,例如,如果我有:
A bgt abc hyi. Abc Ab df h
我必须更换并得到:
A bgt cde nyi. Cde De h
或者尽可能接近,即保持大小写
编辑:由于我对此感到困惑,我将尝试澄清一下:
我要问的是在更换后保持大写的一种方法,我认为这样做不太顺利(没有很好地解释thaat意味着什么),所以我将使用真实的单词给出一个更现实的示例。
可以把它想像成一个福音,可以用它们的同义词代替表达,所以,如果我映射:
didn't achieve success => failled miserably
然后我得到输入的状态:
As he didn't achieve success, he was fired
我会得到
As he failled miserably, he was fired
但是,如果没有大写,那么失败,如果成功或成功被大写,那么不幸的是,如果有超过1个字母大写,那么对应的大写字母
我的主要可能性是(我真的很想考虑的问题)
如果我能够处理已经可以适应的这三个条件,那是我想-这是更简单的方法-当然,如果有深度的解决方案,那将是更好的选择
有任何想法吗?
最佳答案
不知道这将如何工作,但这是我想出的:
string input = "A bgt abc hyi. Abc Ab df h";
Dictionary<string, string> map = new Dictionary<string, string>();
map.Add("abc", "cde");
map.Add("ab df", "de");
string temp = input;
foreach (var entry in map)
{
string key = entry.Key;
string value = entry.Value;
temp = Regex.Replace(temp, key, match =>
{
bool isUpper = char.IsUpper(match.Value[0]);
char[] result = value.ToCharArray();
result[0] = isUpper
? char.ToUpper(result[0])
: char.ToLower(result[0]);
return new string(result);
}, RegexOptions.IgnoreCase);
}
label1.Text = temp; // output is A bgt cde hyi. Cde De h
编辑
阅读修改后的问题后,这是我的修改后的代码(事实证明这与@Sephallia的代码类似..且具有类似的变量名lol)
现在的代码有点复杂..但我认为还可以
string input =
@"As he didn't achieve success, he was fired.
As he DIDN'T ACHIEVE SUCCESS, he was fired.
As he Didn't Achieve Success, he was fired.
As he Didn't achieve success, he was fired.";
Dictionary<string, string> map = new Dictionary<string, string>();
map.Add("didn't achieve success", "failed miserably");
string temp = input;
foreach (var entry in map)
{
string key = entry.Key;
string value = entry.Value;
temp = Regex.Replace(temp, key, match =>
{
bool isFirstUpper, isEachUpper, isAllUpper;
string sentence = match.Value;
char[] sentenceArray = sentence.ToCharArray();
string[] words = sentence.Split(' ');
isFirstUpper = char.IsUpper(sentenceArray[0]);
isEachUpper = words.All(w => char.IsUpper(w[0]) || !char.IsLetter(w[0]));
isAllUpper = sentenceArray.All(c => char.IsUpper(c) || !char.IsLetter(c));
if (isAllUpper)
return value.ToUpper();
if (isEachUpper)
{
// capitalize first of each word... use regex again :P
string capitalized = Regex.Replace(value, @"\b\w", charMatch => charMatch.Value.ToUpper());
return capitalized;
}
char[] result = value.ToCharArray();
result[0] = isFirstUpper
? char.ToUpper(result[0])
: char.ToLower(result[0]);
return new string(result);
}, RegexOptions.IgnoreCase);
}
textBox1.Text = temp;
/* output is :
As he failed miserably, he was fired.
As he FAILED MISERABLY, he was fired.
As he Failed Miserably, he was fired.
As he Failed miserably, he was fired.
*/
关于c# - 在C#中保持大小写不变的情况下替换文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11104750/