简体   繁体   中英

preg_match a programming string

what I want is a regular expression that matches a php string. So that means everything between " and " , excluding the \\" . My expression until now has been

/"([^\\"]*)"/As

but that one is not correct. For example with this string

"te\\"st"

it matches "tes\\ whilst it should match "te\\"st" . I also tried this one:

/"([^\\"].*)"/As

which matches the above string correctly, yet when I have this string "te\\"st"" it matches "te\\"st"" , whilst it should only match "te\\"st"

Any help appreciated!

Here is the regex you want:

(?<!\\)"(?:\\\\|\\"|[^"\r\n])*+"

I can make you a shorter variation, but it will not be as solid.

See the demo .

Explanation

  • The negativelookbehind (?<!\\\\) asserts that what precedes is not a backslash
  • match the opening quote
  • (?:\\\\\\\\|\\\\"|[^"\\r\\n]) matches a double backslash, an escaped quote \\" or any chars that are not quotes and newline chars (assuming a string on one line; otherwise take out the \\r\\n )
  • * repeats zero or more times and the + prevents backtracking
  • " matches the closing quote

To use it:

$regex = '/(?<!\\\\)"(?:\\\\\\\\|\\\\"|[^"\r\n])*+"/';
if (preg_match($regex, $yourstring, $m)) {
    $thematch = $m[0];
    } 
else { // no match...
     }

You can use this pattern:

/\A"(?>[^"\\]+|\\.)*"/s

in php code you must write:

$pattern = '/\A"(?>[^"\\\]+|\\\.)*"/s';

pattern details:

\A     # anchor for the start of the string
"
(?>    # open an atomic group (a group once closed can't give back characters)
    [^"\\]+   # all characters except quotes and backslashes one or more times
  |
    \\.       # an escaped character
)*
"
/s     singleline mode (the dot can match newlines too)

This one matches it:

/"((?:.*?(?:\\")?)*)"/As

Try it live !

What it does:

any number of times, repeat .*? and optional \\" . So it matches all possible scenarios.

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