Reputation: 548
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
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
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
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