如果其值等于零,则替换特定的捕获组值

时间:2014-06-26 06:31:47

标签: c#

如果C#中的值等于0(零),是否可以用其他值替换特定的捕获组值?

Match match = Regex.Match(input, "\b([1-9])([0-9])([0-9]).([0-9])([0-9])([0-9])\b");
if (match.Success)
{
    if(match.Groups[5].Value == "0" || match.Groups[6].Value == "0")
    {

    }
}

基本上我输入的是MHz频率,接受值100.000-199.999。我想要的是如果最后两位数字是零,我想删除它们。例如,如果输入是197.900,我想用197.9替换它。如果是197.990 => 197.99。如果197.090 => 197.09 ......等等。

此外,删除数字后,我想将字符串重写为XXX点XXX ...

Regex.Replace(input, "\b([1-9])([0-9])([0-9]).([0-9])([0-9])([0-9])\b", "$1 $2 $3 point $4 $5 $6");

我只是不确定该怎么做。

3 个答案:

答案 0 :(得分:1)

截断零:

string text = "Frequencies are 193.200 and 194.220 MHz. Sometimes all three digits are used: 195.123";
string output = Regex.Replace(text, @"\b[1-9]\d{2}\.\d{3}\b", m => m.Value.TrimEnd('0'));

输出:

Frequencies are 193.2 and 194.22 MHz. Sometimes all three digits are used: 195.123

截断零并将.替换为point

string text = "Frequencies are 193.200 and 194.220 MHz. Sometimes all three digits are used: 195.123";
string output = Regex.Replace(text, @"\b([1-9]\d{2})\.(\d{3})\b",
                              m => string.Format("{0} point {1}",
                                                 m.Groups[1].Value,
                                                 m.Groups[2].Value.TrimEnd('0')));

输出:

Frequencies are 193 point 2 and 194 point 22 MHz. Sometimes all three digits are used: 195 point 123

要处理0小数部分的数字,例如:196.000,您可以使用以下代码:

string text = "193.200, 194.220, 195.123, 196.000.";
string output = Regex.Replace(text, @"\b([1-9]\d{2})\.(\d)(\d{2})\b",
                              m => string.Format("{0} point {1}{2}",
                                                 m.Groups[1].Value,
                                                 m.Groups[2].Value,
                                                 m.Groups[3].Value.TrimEnd('0')));

输出:

193 point 2, 194 point 22, 195 point 123, 196 point 0.

答案 1 :(得分:0)

试试这个:

string input = "199.090";
string result = String.Empty;
Match match = Regex.Match(input, "([1-9])([0-9])([0-9]).([0-9])([0-9])([0-9])");
if (match.Success)
{
    result = match.ToString().TrimEnd(new [] {'0'});
}
result.Dump();

Dump()的输出:

199.09

答案 2 :(得分:0)

您可以使用以下代码

input.TrimEnd('0');

这将删除尾随0