开发者

Regex Replace Between Quotations

开发者 https://www.devze.com 2022-12-24 20:56 出处:网络
I am wondering on where to begin to perform the following replace in regex: Read file (.cs file) Replace anything between quotations (\"e.g:\") with its uppercase version (\"E.G:\")

I am wondering on where to begin to perform the following replace in regex:

  1. Read file (.cs file)
  2. Replace anything between quotations ("e.g:") with its uppercase version ("E.G:")

By example:

string m = "stringishere";

Becom开发者_如何学Goes

string m = "STRINGISHERE";

Thanks in advance,

Kyle


It's not stated in your question so I'll provide a possible solution for single-line quotations:

public static void Main(string[] args)
{
    const string MatchQuotedExp = @"(\x22|\x27)((?!\1).|\1{2})*\1";

    Regex regex = new Regex(MatchQuotedExp);

    string input = @"""Foo"" Bar ""Foo"" Bar ""Foo""!
        ""Bar"" Foo ""Bar"" Foo ""Bar""!";

    foreach (Match match in regex.Matches(input))
    {
        input = Regex.Replace(
            input, 
            match.Value, 
            match.Value.ToUpperInvariant());
    }

    Console.WriteLine(input);
}

For multi-line quotation support add RegexOptions.Singleline when creating the regex.

With multi-line support, the input:

// "Foo" Bar "Foo" Bar "Foo"!
// "Bar" Foo "Bar" Foo "Bar"! "Multi
// line" blah

will be converted to:

// "FOO" Bar "FOO" Bar "FOO"!
// "BAR" Foo "BAR" Foo "BAR"! "MULTI
// LINE" blah

Also note that this will blow up if ANY of the quotations contain an odd number of " inside. :)


Since a .cs file may contain comments like

 // Look, lonely double quote: " Take that, Regex parser! 

what you are asking will be very difficult to do with Regex.


Assuming your string don't have " inside.

Regex r = new Regex('"[^"]+"');
string output = r.Replace(input,m=>m.Groups[0].ToUpper());
0

精彩评论

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

关注公众号