Sameer
Sameer

Reputation: 548

How do I geta string of text that lies between two '{'parenthesis'}' set using .NET?

I have a string "Item Name {Item Code} {Item ID}" and I want to extract the text between the first occurrence of {} i.e. {Item Code} , I used

Regex.Match( "Item Name {Item Code} {Item ID}", @"\{([^)]*)\}").Groups[0].Value

but I got "{Item Code} {Item ID}"

How would I do this?

Upvotes: 1

Views: 127

Answers (3)

aelor
aelor

Reputation: 11126

\{([^)]*?)\}")

make it lazy, it will work

IMHO use a regex like this: \{(.*?)\} your regex has a useless [^)], the meaning of this along with * would be to select upto the ) char, but there is no ). So, better off with my regex.

demo here : http://regex101.com/r/eM6iL0

Upvotes: 3

Soner Gönül
Soner Gönül

Reputation: 98868

Using regex is better but since you tagged with substring, here is the way;

string s = "Item Name {Item Code} {Item ID}";
int index1 = s.IndexOf('{');
int index2 = s.IndexOf('}') ;
string result = s.Substring(index1 + 1, index2 - index1 - 1);
Console.WriteLine(result);

Here a demonstration.

IndexOf method gets the index of the first occurrence of specified character.

Upvotes: 0

Qtax
Qtax

Reputation: 33928

It should be {([^}]*)}. Not a ) in the character class, but a }. Meaning, match everything except (until) a }.

You may want to use {([^{}]+)} when you have input like foo {bar {baz} not match {}.

Upvotes: 2

Related Questions