搜索子字符串的字符串

Jos*_*osh 4 c# regex

我需要搜索一个特定子字符串的大字符串.子字符串将从一开始,Testing=但双引号内的所有内容都可能不同,因为它是用户登录.

所以我需要的子串的例子是

Testing="network\smithj"  
Run Code Online (Sandbox Code Playgroud)

要么

Testing="network\rodgersm"  
Run Code Online (Sandbox Code Playgroud)

我的要求有意义吗?我怎么能在C#中做到这一点?

jjn*_*guy 10

这是正则表达式的一个很好的应用.

"Testing=\"[^\"]*\""
Run Code Online (Sandbox Code Playgroud)

你会像这样使用它:

Regex reg = new Regex("Testing=\"[^\"]*\"");
string login = reg.Match(yourInputString).Groups[0].Value;
Run Code Online (Sandbox Code Playgroud)

以上内容适用于您的两个测试用例.

如果你不熟悉它,维基百科有一篇关于正则表达式的精彩文章.如果您搜索谷歌,您可以找到有关如何在C#中使用正则表达式的丰富信息.


Jon*_*eet 9

就像是:

const string Prefix = "Testing=\"";

static string FindTestingSubstring(string text)
{
    int start = text.IndexOf(Prefix);
    if (start == -1)
    {
        return null; // Or throw an exception
    }
    int end = text.IndexOf('\"', start + Prefix.Length);
    if (end == -1)
    {
        return null; // Or throw an exception
    }
    return text.Substring(start + Prefix.Length, end - start - Prefix.Length);
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用正则表达式 - 但是当模式相当简单时,我个人更喜欢简单的字符串操作.这取决于你对正则表达式的舒适程度:)