匹配字符串时,regex如何忽略转义引号? [英] How can regex ignore escaped-quotes when matching strings?

查看:137
本文介绍了匹配字符串时,regex如何忽略转义引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个正则表达式,它将匹配一切,但是没有被转义的撇号。考虑以下内容:

 <?php $ s ='大家好,我们现在就准备好了。 ?> 

我的目标是编写一个正则表达式,它将基本上匹配它的字符串部分。我正在想一些例如

  /.*'([^'])。* / 

为了匹配一个简单的字符串,但我一直在努力弄清楚如何得到一个负面的lookbehind工作在撇号以确保它之前没有反斜杠...



任何想法?



- JMT

解决方案

 <?php 
$ backslash ='\\' ;

$ pattern =<<<< PATTERN
#([:'])(?:{$ backslash} {$反斜杠}?+。)*?{$反斜杠} 1#
PATTERN;

foreach (array(
<?php \ $ s ='大家好,我们现在就准备好了''?'',
'<?php $ s = 大家好,我们现在就准备好了;?>',
xyz'a\\'bc\\d'123,
x ='我的字符串以反斜杠\\\\';
)为$ subject结束; {
preg_match($ pattern,$ subject,$ matches);
echo $ subject,'=> ',$ matches [0],\\\
\\\
;
}

打印

 <?php $ s ='大家好,我们现在就准备好了。 ?> => 大家好,我们现在就准备好了

<?php $ s =大家好,我们现在就准备好了;?> =>大家,我们现在就准备好了。

xyz'a\'bc\d'123 => 'a\'bc\d'

x ='我的字符串以反斜杠\\'结尾; => '我的字符串以反斜杠\\''


结束

I'm trying to write a regex that will match everything BUT an apostrophe that has not been escaped. Consider the following:

<?php $s = 'Hi everyone, we\'re ready now.'; ?>

My goal is to write a regular expression that will essentially match the string portion of that. I'm thinking of something such as

/.*'([^']).*/

in order to match a simple string, but I've been trying to figure out how to get a negative lookbehind working on that apostrophe to ensure that it is not preceded by a backslash...

Any ideas?

- JMT

解决方案

<?php
$backslash = '\\';

$pattern = <<< PATTERN
#(["'])(?:{$backslash}{$backslash}?+.)*?{$backslash}1#
PATTERN;

foreach(array(
    "<?php \$s = 'Hi everyone, we\\'re ready now.'; ?>",
    '<?php $s = "Hi everyone, we\\"re ready now."; ?>',
    "xyz'a\\'bc\\d'123",
    "x = 'My string ends with with a backslash\\\\';"
    ) as $subject) {
        preg_match($pattern, $subject, $matches);
        echo $subject , ' => ', $matches[0], "\n\n";
}

prints

<?php $s = 'Hi everyone, we\'re ready now.'; ?> => 'Hi everyone, we\'re ready now.'

<?php $s = "Hi everyone, we\"re ready now."; ?> => "Hi everyone, we\"re ready now."

xyz'a\'bc\d'123 => 'a\'bc\d'

x = 'My string ends with with a backslash\\'; => 'My string ends with with a backslash\\'

这篇关于匹配字符串时,regex如何忽略转义引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆