首页 > 解决方案 > 如何在字符串值之间获取字符串值

问题描述

“该示例适用于 C# - 值是 - 这里是值。” 我想从我尝试过的这个字符串值中获取值(这里是值),但是当字符串值中有两个(-)破折号并且无法获取值时,它会给我错误。我怎么能做到这一点,我已经尝试过。

        String St = "The example is for C# - The value is -Default ID.";

        int pFrom = St.IndexOf(" - ") + "-  ".Length;
        int pTo = St.LastIndexOf(" . ");
        String result = St.Substring(pFrom, pTo - pFrom);

当句子中只有一个(-)时,它可以正常工作。如何从字符串中获取值(默认 ID)。

标签: c#winforms

解决方案


您可以使用正则表达式模式[^-]*$

例子

var input = "The example is for C# - The value is -Default ID.";
var match = Regex.Match(input, @"[^-]*$");
if (match.Success)
    Console.WriteLine(match.Value);

输出

Default ID.

完整的演示在这里


解释

在此处输入图像描述

可视化

在此处输入图像描述


推荐阅读