简体   繁体   中英

Regex pattern issue c#

I have a little trouble here. I am trying to find a Regex which will match all fallowing examples:

  • Method( "Team Details" )

    Should return: Team Details

  • Method( @"Team details item

    and more

    and More" )

    Should return: Team Details item and more and more

  • Method( "Team \\"Details\\"" )

    Should return: Team "Details"

  • Method( @"Team ""Details""" )

    Should return: Team "Details"

  • Method( @"Team

    ""Details""" )

    Should return: Team

    "Details"

I managed to create a regex pattern:

Method\(.*\"(.*)\".*\)

whcih is working in the first example and partially second one, but I found it very difficult to create one pattern for all 5 examples. Any help ?

Cheers

. only matches non-newline characters by default, so your regex will fail if the match spans multiple lines. If you change that behavior by using the (?s) mode modifier, you need to make sure that your matches don't become too long.

The simplest way to achieve that would be to make the * quantifier lazy.

(?s)Method\(.*?\"(.*?)\".*?\)

That would work on your examples, but it would fail if there were any closing parentheses within the "Details..." string.

You could make it more robust by restricting the set of allowed characters, considering escaped or doubled quotes:

Method\([^\"]*\"((?:""|\\.|[^\"\\]+)*)\"[^\"]*\)

Test it live on regex101.com .

What this can't do is change the contents of the match (ie, remove extra whitespace or convert quotes, as you seem to expect) - that can't be done in a single regex. But you can apply more transformation steps to the matches of this regex and process those further.

Use an expression like so: Method\\(\\s*@?(.+?)\\) (example here ). You will need to include the s flag. This will allow the period character to also match new lines, which is something you require for your second example.

Once that you have the string you are after (contained within a regex group), you can use the usual replace operations to format the text as you would like. This should produce a solution which is more flexible and easier to follow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM