ruqo
ruqo

Reputation: 65

How can I escape these quotes in regex expressions?

I have a string text which is like:

  "ruf": "the text I want",
     "puf":

I want extract the text inside the quotes.

tried this :

         string cg="?<=\"ruf\":\")(.*?)(?=\",puf";
         Regex g = new Regex(cg);

It didnt work.

Upvotes: 0

Views: 51

Answers (3)

Braj
Braj

Reputation: 46871

Try with below regex:

(?<="ruf":\s\")[^"]*

Online demo

String literals for use in programs:

C#

@"(?<=""ruf"":\s\"")[^""]*"

output:

the text I want

Pattern description:

  (?<=                     look behind to see if there is:
    "ruf":                   '"ruf":'
    \s                       whitespace (\n, \r, \t, \f, and " ")
    \"                       '"'
  )                        end of look-behind
  [^"]*                    any character except: '"' (0 or more times
                           (matching the most amount possible))

Regular expression visualization

Debuggex Demo


EDIT

Can you add puf. Because it is a long text which has multiple quotes in it

If you are looking till "puf" is found then try below regex:

(?<="ruf":\s\")[\s\S]*(?=",\s*"puf")

Online demo

String literals for use in programs:

C#

@"(?<=""ruf"":\s\"")[\s\S]*(?="",\s*""puf"")"

Upvotes: 3

zx81
zx81

Reputation: 41848

Do it like this:

var myRegex = new Regex(@"(?s)(?<=""ruf"": "")[^""]*(?=\s*""puf"")");
string resultString = myRegex.Match(yourString).Value;
Console.WriteLine(resultString);

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174834

You could try the below regex with s modifier,

/(?<=\"ruf\": \")[^\"]*(?=\",.*?\"puf\":)/s

DEMO

With the s modifier, dot matches even newline character also.

Upvotes: 1

Related Questions