1
\$\begingroup\$

My purpouse is to select every character which is surrounded by { and }, this is easily achievable using this regexp {\w*}.

I've developed an extenstion method for strings:

 public static IEnumerable<string> ObtainTokens(this string originalString)
 {
 Regex expression = new Regex(@"{\w*}");
 foreach (Match element in expression.Matches(originalString))
 {
 //Exclude the brackets from the returned valued
 yield return Regex.Replace(element.Value, @"{*}*", "");
 }
 }

Is there a way to get rid of of Regex.Replace? Returning the values as IEnumerable is a good choice?

asked Dec 13, 2012 at 9:34
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Modify your regexp: {(\w*)} and then replace:

yield return Regex.Replace(element.Value, @"{*}*", "");

with

yield return element.Groups[1].Value;

ps: full code is avaialbe here

answered Dec 13, 2012 at 9:48
\$\endgroup\$
2
  • \$\begingroup\$ By applying your suggestion on the test string {THIS} is a {TEST} the response is an IEnumerable<string> containing two empty string. \$\endgroup\$ Commented Dec 13, 2012 at 9:54
  • 1
    \$\begingroup\$ regex has beed updated to capture groups: {(\w*)} \$\endgroup\$ Commented Dec 13, 2012 at 10:16

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.