简体   繁体   中英

C# removing string before/after delimiter

I've seen a lot of post using RegEx to remove part of string before or after using some delimiter. The fact is, I don't understand RegEx and have a case a little strange. Here is the situation :

I have a string that can be :

string test1 = (something)...keepThisOne
string test2 = keepThisOne...(something)
string test3 = (something)...keepThisOne...(somethingelse)

So far I got :

string test = testx.Substring(testx.LastIndexOf('.')+1);

but it does not work even for the string test1

I know RegExp can be use to remove everything between paranthesis and all the "..." in this string. My question is how can I achieve that with RegExp without knowing in advance what kind of string test I will get, and what does it the RegExp means ??

The output needed is the get only :

string result = keepThisOne

whatever the string test is used.

Try with Regex :

Regex rgx = new Regex(@"\.*\(\w*\)\.*");
string result = rgx.Replace(input, string.Empty);

Regex will generate the output as

keepThisOne
keepThisOne
keepThisOne

You can run the various scenario in this fiddle.

This does not need RegEx:

string test = testx.Split(new string[] { "..." }, StringSplitOptions.RemoveEmptyEntries)
    .Single(s => !s.StartsWith("(") && !s.EndsWith(")"));

This splits the original string by the dots and only returns the part that does not start and end with parentheses.

This is a LINQ solution working in all 3 cases:

var res = String.Join("", Char.IsLetter(input.First()) ?
                          input.TakeWhile(c => Char.IsLetter(c)) :
                          input.SkipWhile(c => c != '.')
                               .SkipWhile(c => c == '.')
                               .TakeWhile(c => Char.IsLetter(c)));

You can use this code (adapted from another answer ):

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        Regex rgx = new Regex(@"…*\.*\(\w*\)\.*…*");
        Console.WriteLine(rgx.Replace("(something)…keepThisOne", string.Empty));
        Console.WriteLine(rgx.Replace("keepThisOne…(something)", string.Empty));
        Console.WriteLine(rgx.Replace("(something)...keepThisOne…(somethingelse)", string.Empty));

    }
}

Try it in a fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM