开发者

C# Equivalent for JS RegEx Expression

开发者 https://www.devze.com 2023-03-20 04:59 出处:网络
What\'s the C# equivalent of this JavaScript Regular Expression? str.replace(/(\\w)\\w*/g, \"$1\"); Javascript Input + Result (Desired):

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!
Resul开发者_开发百科t: \1 \1 \1!

Any other ideas?


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.)


var result = Regex.Replace(input, @"(?<x>\w)\w*", @"${x}");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号