简体   繁体   中英

Find string inside single and double quotation marks using regex

How to find string between "" and '' using regex. Just I want to create a function using PHP preg_match_all() function that will match all the static strings in a file, so probably we are creating a string using "" and '' so I need to find all such strings from a file.

You should be aware that inside those quoted "entities" you may find escaped quotes. The best way to match those strings is using a regex like this:

(?s)'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"

See demo

Sample code:

$re = "/(?s)'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"/"; 
$str = "\"string 'c' \" string \" \" and ' string \"ste\" \' '"; 
preg_match_all($re, $str, $matches);

IDEONE demo

This will match " and ' strings:

/((?<!\\)["']).+?(?<!\\)\1/m

You can see the explanation of the regular expression on this page .

This regex will do what you want to do, just beware that you can't really identify the semantic differences between the apostrophe in "you're" from 'you're string'.

preg_match_all(
    "|(['\"])([^\"]*)(\1)|g",
    'This \'is a\' small "demo of what" you\'re trying, to "do"!'
);

Reference

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