0

What's the C# equivalent of this JavaScript Regular Expression?

str.replace(/(\w)\w*/g, "$1");

Javascript Input + Result (Desired):

Input:  I like pie!
Result: i l p!

C# Input + Result (Using Tim's Version posted below):

Input:  I like pie!
Result: \1 \1 \1!

Any other ideas?

6
  • 2
    So you want to convert something that you don't understand into something new that you don't understand. How about learning something about regular expressions instead? Commented Jul 13, 2011 at 12:40
  • 1
    Coming to the defence of the OP: You need quite a bit of knowledge about the different regex flavors in order to correctly translate them between vastly different implementations such as JS and .NET. If he had just copied the regex into a C# string, the result would have been subtly wrong. Commented Jul 13, 2011 at 12:45
  • Actually, that piece of code replaces every word in a string with it's first character. I'm not sure how it would translate to C# as RegEx.Replace() in C# would simply replace the matches with whatever you input. Using "$1" is JavaScript specific. Commented Jul 13, 2011 at 12:45
  • @Tim Pietzcker: That's perfectly correct. However, just posting a regex here with the question "how to convert?" without further explanation of what is to be achieved or what it does match imho sounds like the original regex was just copied from e.g. a cookbook. Not mentioning what has been tried already then sounds imho like @Mr. Smith did not even try to look at the documentation of the flavors. Of course I can be wrong with my assumption, but looking at the rating indicates to me that I am not the only misunderstander. Commented Jul 13, 2011 at 13:01
  • @phresnel: That's not perfectly correct. See my comments on his code. His answer did however point me in the right direction and is why I accepted his answer. You should be so quick to judge phresnel. Hope you have a better day. Commented Jul 13, 2011 at 13:04

2 Answers 2

4
resultString = Regex.Replace(subjectString, "([A-Z0-9_])[A-Z0-9_]*", "$1", RegexOptions.IgnoreCase);

This change is necessary because \w matches a lot more in .NET regexes than in JavaScript regexes.

(Unless you also want to match words that contain non-ASCII letters/digits, in which case `@"(\w)\w*" would be better.)

Sign up to request clarification or add additional context in comments.

1 Comment

@Mr. Smith: Right, sorry. Thanks for the heads-up!
1
var result = Regex.Replace(input, @"(?<x>\w)\w*", @"${x}");

Comments

Your Answer

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.