Anoushka Seechurn
Anoushka Seechurn

Reputation: 2256

Extracting a substring between two characters in a string C#

I have a generated string somewhat like

($AverAbandCalls$+$TotalInboundCalls$)*50+$TotalOutboundCalls$

I want to get everythng that is between the $ signs. How do I proceed ?

I know it can be done using the .Split But this gives the final answer after much jungling with the strings.

I want to know If there is a way to do this in an easier way.

Upvotes: 1

Views: 6809

Answers (5)

uzrgm
uzrgm

Reputation: 395

Here is a simple method without any Regex:

string SubstringBetweenSymbols(string str, char preSymbol, char postSymbol)
    {
        int? preSymbolIndex = null;
        int? postSymbolIndex = null;


        for (int i = 0; i < str.Length; i++)
        {
            if (i == 0 && preSymbol == char.MinValue)
            {
                preSymbolIndex = -1;
            }
            if (str[i] == preSymbol && !(preSymbolIndex.HasValue && preSymbol == postSymbol))
            {
                preSymbolIndex = i;
            }
            if (str[i] == postSymbol && preSymbolIndex.HasValue && preSymbolIndex != i)
            {
                postSymbolIndex = i;
            }
            if (i == str.Length - 1 && postSymbol == char.MinValue)
            {
                postSymbolIndex = str.Length;
            }



            if (preSymbolIndex.HasValue && postSymbolIndex.HasValue)
            {
                var result = str.Substring(preSymbolIndex.Value + 1, postSymbolIndex.Value - preSymbolIndex.Value - 1);
                return result;
            }
        }

        return string.Empty;
    }

Pre and Post symbols maybe be a char.MinValue, which means beginning of the string or string ending.

Upvotes: 1

Alex Filipovici
Alex Filipovici

Reputation: 32541

Try this regular expression:

(?:\$).*?(?:\$)

Since you are using .NET, you might also try balancing groups:

(?<open>\$).*?(?<final-open>\$)

Example:

var input = @"($AverAbandCalls$+$TotalInboundCalls$)*50+$TotalOutboundCalls$";
var reg = new Regex(@"(?<open>\$).*?(?<final-open>\$)");
var matches = reg.Matches(input).Cast<Match>()
    .Select(m=>m.Groups["final"].Value).ToList();

foreach (var item in matches)
{
    Console.WriteLine(item);
}

Which outputs:

AverAbandCalls
TotalInboundCalls
TotalOutboundCalls

Upvotes: 5

Roy Dictus
Roy Dictus

Reputation: 33139

Use a Regex (regular expression). This contains a description of the pattern to match -- in your case, a dollar sign, a number of non-dollar sign characters, and another dollar sign.

In .NET, Regex support is in the System.Text.RegularExpressions library, so you'll have to reference that in your code.

Here is a simple example:

string pattern = "\$([^\$]*)\$";
var matches = Regex.Matches(input, pattern);

Upvotes: 2

user2968347
user2968347

Reputation: 21

You can do like this

using System.Text.RegularExpressions;
using System;
public class Test
{
        public static void Main(){
                string s = "My name is $Dave$ and I am $18$ years old";
                Regex r = new Regex(@"$(.+?)$");
                MatchCollection mc = r.Matches(s);
                Console.WriteLine("Name is " + mc[0].Groups[1].Value);
                Console.WriteLine("Age is " + mc[1].Groups[1].Value);
        }
}

Upvotes: 0

Matt Mitchell
Matt Mitchell

Reputation: 41823

 string input = "($AverAbandCalls$+$TotalInboundCalls$)*50+$TotalOutboundCalls$";
 IEnumerable<string> matches =
        Regex.Matches(input, @"\$([^\$]+)\$")
        .OfType<Match>()
        .Select(m => m.Groups[1].Value);

This Regex matches the literal $ character using "\$" then one or more characters than are not a $ using "[^\$]+" and then another $ using "\$" again.

It surrounds the bit in between using round brackets "([^\$]+)" to make it a Regex Group which is easy to grab.

There will already be a default Regex Group (i.e. the entire match) so we grab the Group at index 1.

Upvotes: 0

Related Questions