从大字符串中获取子字符串或字符串标记化

本文关键字:字符串 获取 | 更新日期: 2023-09-27 18:07:36

我有这样的刺痛:

(Project in ("CI") and Status in ("Open") and issueType in ("Action Item")) or issueKey = "GR L-1" order by Created asc

我想解析如下:

string st1 = "CI";
string str2 = "Open";
string str3 = "Action Item";

我试过这样做:http://www.codeproject.com/Articles/7664/StringTokenizer

这就是我尝试过的:

 string input = @"(Project in (""CI"") and Status in (""Open"") and issueType in (""Action Item"")) or issueKey = ""GR L-1"" order by Created asc";
        string sub = input.Substring(13, 3);

注意:我要检索的字符串可以动态更改。

我没有得到预期的结果。你能请一位导游吗?

从大字符串中获取子字符串或字符串标记化

实现这一点的最佳方法是使用正则表达式,请尝试以下代码

using System;
using System.Text.RegularExpressions;
public class RegexTest
{
    public static void Main(string[] args)
    {
        var sourcestring = @"(Project in (""CI"") and Status in (""Open"") and issueType in (""Action Item"")) or issueKey = ""GR L-1"" order by Created asc";
        var mc = Regex.Matches(sourcestring,
                               @"'(""(?<word>[A-Za-z0-9's]+)""')");
        foreach (Match m in mc)
        {
            foreach (Capture cap in m.Groups["word"].Captures)
            {
                Console.WriteLine(cap.Value);
            }
        }
        Console.ReadLine();
    }
}

输出结果将是您要查找的单词。

CI 
Open 
Action Item

在此处测试代码https://dotnetfiddle.net/RHpf3n

您的需求看起来好像要提取("&CCD_ 2。如果你发现Regex有点"吓人",你仍然可以使用你尝试的String.Substring()方法,你只需要将它与String.IndexOf()结合起来,就可以得到("&"),并将这些值提供给String.Substring(),而不是尝试对它们进行硬编码。

这样做的一种方法可能如下:

using System;
public class Program
{
    public static void Main()
    {
        string input = @"(Project in (""CI"") and Status in (""Open"") and issueType in (""Action Item"")) or issueKey = ""GR L-1"" order by Created asc";
        // Find the open paren & quote
        int startIndex = input.IndexOf("('"", 0);
        // Loop until we don't find an open paren & quote
        while (startIndex > -1)
        {
            // Find the closing paren & quote
            int endIndex = input.IndexOf("'")", startIndex);
            Console.WriteLine(input.Substring(startIndex + 2, endIndex - startIndex - 2));
            // Find the next open paren & quote
            startIndex = input.IndexOf("('"", endIndex);
        }
    }
}

结果:

CI
Open
Action Item

Fiddle演示