Regex pattern to choose data BETWEEN matching quotation marks

后端 未结 5 915
悲哀的现实
悲哀的现实 2020-12-19 08:59

Suppose I had the following string I wanted to run a Regular expression on:

This is a test string with \"quotation-marks\" within it.
The \"problem\" I am ha         


        
5条回答
  •  孤城傲影
    2020-12-19 09:56

    You are having the same problem as someone who is trying to match HTML or opening and closing parentheses, regex can only match regular languages and knowing which " is a closing and an opening one is out of its reach for anything but the trivial cases.

    EDIT: As shown in Vasili Syrakis's answer, sometimes it can be done but regex is a fragile solution for this type of problem.

    With that said, you can convert your problem in the trivial case. Since you are using .NET, you can simply match every quoted string and use the overload that takes a match evaluator.

    Regex.Replace(text, "\".*?\"", m => m.Value.Replace("-", " "))
    

    Test:

    var text = @"This is a test string with ""quotation-marks"" within it.
    The ""problem"" I am having, per-se, is ""knowing"" which ""quotation-marks""
    go with which words.";
    
    Console.Write(Regex.Replace(text, "\".*?\"", m => m.Value.Replace("-", " ")));
    //This is a test string with "quotation marks" within it.
    //The "problem" I am having, per-se, is "knowing" which "quotation marks"
    //go with which words. 
    

提交回复
热议问题