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

时间:2015-08-12 00:24:21

标签: c# string

我有这样的刺痛:

(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);

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

我没有达到预期的效果。你能指导一下吗?

2 个答案:

答案 0 :(得分:1)

实现这一目标的最佳方法是使用正则表达式,尝试此代码

var currentTime = delta;
var timer = setInterval(function () {
     if (currentTime == 0) {
         clearInterval(timer);
     }
     else {
         currentTime--;
         console.log(currentTime);
     }
}, 1000);

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

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();
    }
}

测试代码here https://dotnetfiddle.net/RHpf3n

答案 1 :(得分:0)

您的要求看起来好像要提取("&amp;之间找到的任何数据。 ")。如果您发现Regex有点“令人生畏”,您仍然可以使用您尝试的String.Substring()方法,您还必须将其与String.IndexOf()结合使用,以获得{{1}的索引位置}&amp; ("并将这些值提供给"),而不是尝试对其进行硬编码。

这样做的一种方式如下:

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);
        }
    }
}

Fiddle Demo

相关问题