如何在C#中的两个特定字符之间获取字符串?

时间:2016-04-08 17:58:13

标签: c# regex string

string test = "item_id - description (moreInfo)"

我想抓住说明。

测试将始终以“item_id - ”

开头

测试将始终以“(xxx)”

结束

测试可以在描述中包含任何内容,如空格,破折号等。

所以基本上我需要在第一个“ - ”UNTIL最后一个“(”

之后捕获字符串

我很难过。

5 个答案:

答案 0 :(得分:3)

using System;
using System.Text.RegularExpressions;

public class Test
{
    public static void WithRegex(string test)
    {
        string extracted = new Regex(@"- ?(.*) ?\([^\(]+$").Match(test).Groups[1].Value;
        Console.WriteLine("Extracted: {0}", extracted);
    }

    public static void WithoutRegex(string test)
    {
        string extracted = test.Substring(test.IndexOf("-") + 1, test.LastIndexOf("(") - test.IndexOf("-") - 1).Trim();
        Console.WriteLine("Extracted: {0}", extracted);
    }

    public static void Main()
    {
        string test = "item_id - description (something else) !onuth - hi you (moreInfo)";
        WithRegex(test);
        WithoutRegex(test);
    }
}

打印

Extracted: description (something else) !onuth - hi you
Extracted: description (something else) !onuth - hi you

答案 1 :(得分:0)

这可以让你开始走上正确的道路:

var reg = new Regex(@"^item_id - (.+) \(moreInfo\)$");
string test = "item_id - description (moreInfo)";
var match = reg.Match(test);

if(match.Success)
{
    if(match.Groups.Count > 1)
    {
        var group = match.Groups[1];
        System.Diagnostics.Debug.Print(group.Value); // prints your description....
    }
}

答案 2 :(得分:0)

Adder.java

<强> Ideone Demo

答案 3 :(得分:0)

您可以使用IndexOf

组合LastIndexOfSubstring来完成此操作

test.Substring(test.IndexOf("- ") + 2, test.LastIndexOf("(") - (test.IndexOf("- ") + 2));

答案 4 :(得分:0)

不使用正则表达式:

public void SelectPartOfString()
{
    string test = "item_id - description (moreInfo)";
    int beginIndex = test.IndexOf("-") + 1; //char immediately after `-`
    int endIndex = test.LastIndexOf("(") - 1; //char immediately before last `(`

    string subString = test.Substring(beginIndex, (endIndex - beginIndex)).Trim(' '); //remove leading/trailing spaces

    Console.WriteLine(subString);
}