[英]Replacing digits in C# string
我正在尝试使用正则表达式对字符串做一些工作,但我遇到了一些困难。 我的目标是用字符替换字符串中的数字,特别是如果字符串中有一组数字,我想用*
替换整组数字。 如果只有一个数字,我想用?
.
例如,如果我有字符串“test12345.txt”,我想把它变成“test*.txt”,但如果我有“test1.txt”,我想把它变成“test?.txt” .
我试过了
Regex r = new Regex(@"\d+", RegexOptions.None);
returnString = r.Replace(returnString, "*");
但是,这取代取代,甚至一个单一的数字对自己有*
使用Regex.Replace这很容易
string input = "test12345.txt";
// replace all numbers with a single *
string replacedstar = Regex.Replace( input, "[0-9]{2,}", "*" );
// replace remaining single digits with ?
string replacedqm = Regex.Replace( input, "[0-9]", "?" );
这样做,首先它将匹配两个以上的数字并用*
替换整个块,第二条语句用于如果有单个数字,它将替换为?
'
var newFileName = Regex.Replace(fileName, @"\d{2,}", "*");
newFileName = Regex.Replace(fileName, @"\d", "?");
希望这可以帮助。
使用两个正则表达式执行此操作:
*
替换\\d{2,}
,?
替换\\d
. static string ReplaceNumbers(string text)
{
string output = Regex.Replace(text, @"\d{2,}", "*");
output = Regex.Replace(output, @"\d", "?");
return output;
}
int n1 = Convert.ToInt32(number.Text);
int n2 = Convert.ToInt32(replace.Text);
int n3 = Convert.ToInt32(othernumber.Text);
int temp;
int result = 0;
int i = 1;
while (n1 > 0)
{
temp = n1 % 10;
if (n2 == temp)
{
result += n3 * i;
}
else
{
result = result + temp * i;
}
i *= 10;
n1 = n1 / 10;
}
afterswap.Text = Convert.ToString(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.