如何检查字符串是否包含“(1)”,如果包含,则将数字增加1?

时间:2019-12-05 13:08:43

标签: c# string

如果任何给定的字符串的末尾包含“(”,后跟数字,+“)”,我想将该值增加一。如果不是,请添加“(1)”。

我已经尝试过使用string.Contains()之类的东西,但是由于()中的值可能不同,所以我不知道如何总是这样搜索并获取数字。

4 个答案:

答案 0 :(得分:7)

要在字符串末尾找到括号内的数字,并增加b 1,请尝试以下操作:

Regex.Replace(yourString, @"(?<=\()\d+(?=\)$)", match => (int.Parse(match.Value) + 1).ToString());

说明:

(?<=\()是正向后看,它与方括号匹配,但不包括在匹配结果中。

\d+匹配一个或多个数字。

(?=\)$)是一个积极的前瞻,与字符串末尾的右括号匹配。

要添加数字(如果不存在),请先测试匹配项:

string yourString = "A string with no number at the end";
string pattern = @"(?<=\()\d+(?=\)$)";
if (Regex.IsMatch(yourString, pattern))
{
    yourString = Regex.Replace(yourString, pattern, match => (int.Parse(match.Value) + 1).ToString());
}
else
{
    yourString += " (1)";
}

答案 1 :(得分:3)

您可以尝试正则表达式npx create-react-app my-app Match所需的片段,例如

Replace

结果:

  using System.Text.RegularExpressions;

  ...

  string[] tests = new string[] {
    "abc",
    "def (123)",
    "pqr (123) def",
    "abs (789) (123)",
  };

  Func<string, string> solution = (line) =>
    Regex.Replace(line, 
      @"\((?<value>[0-9]+)\)$", 
      m => $"({int.Parse(m.Groups["value"].Value) + 1})");

  string demo = string.Join(Environment.NewLine, tests
    .Select(test => $"{test,-20} => {solution(test)}"));

  Console.Write(demo);

如果我们放

abc                  => abc              # no numbers
def (123)            => def (124)        # 123 turned into 124
pqr (123) def        => pqr (123) def    # 123 is not at the end of string
abs (789) (123)      => abs (789) (124)  # 123 turned into 124, 789 spared

编辑:如果我们没有任何匹配项,则要放 Func<string, string> solution = (line) => { Match m = Regex.Match(line, @"\((?<value>[0-9]+)\)$"); return m.Success ? line.Substring(0, m.Index) + $"({int.Parse(m.Groups["value"].Value) + 1})" : line + " (1)"; }; ,可以尝试(1)并替换匹配的文本:

Match

答案 2 :(得分:2)

string s = "sampleText";
string pattern = "[(]([0-9]*?)[)]$";

for (int i = 0; i < 5; i++)
{
    var m = Regex.Match(s, pattern);
    if (m.Success)
    {
        int value = int.Parse(m.Groups[1].Value);
        s = Regex.Replace(s, pattern, $"({++value})");
    }
    else
    {
        s += "(1)";
    }

    Console.WriteLine(s);
}

答案 3 :(得分:1)

如果我理解正确,那么您会有诸如以下字符串:

string s1 = "foo(12)"
string s2 = "bar(21)"
string s3 = "foobar" 

您想获得以下信息:

IncrementStringId(s1) == "foo(13)" 
IncrementStringId(s2) == "bar(22)" 
IncrementStringId(s3) == "foobar(1)"

您可以使用以下方法完成此操作

public string IncrementStringId(string input)
{
    // The RexEx pattern is looking at the very end of the string for any number encased in paranthesis
    string pattern = @"\(\d*\)$";
    Regex regex = new Regex(pattern);
    Match match = regex.Match(input);
    if (match.Success)
        if (int.TryParse(match.Value.Replace(@"(", "").Replace(@")", ""), out int index))
            //if pattern in found parse the number detected and increment it by 1
            return Regex.Replace(input, pattern, "(" + ++index + ")");
    // In case the pattern is not detected add a (1) to the end of the string
    return input + "(1)";
}

请确保您使用的是包含Regex类的System.Text.RegularExpressions命名空间。