0

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

1
  • A good way to solve this type of problem is to create 1 regular expression for each match and then just use (regexp1|regexp2|regexp3) Commented Jan 25, 2016 at 12:09

2 Answers 2

2

. 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 (i. e., 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.

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.