正则表达式匹配特定符号' - " ()* ,. :...; ? `

时间:2017-02-14 14:41:17

标签: php regex symbols pos-tagger

我想构建一个将这些特定符号标记为" SYM"的正则表达式。因此,我在php中构建一个正则表达式,它将仅匹配此特定符号。是否有任何接受这些符号的正则表达式?

'   -   "   (   )  *  ,  .   :  …  ;  ?  `

输出应该是这样的: ' \ SYM - \ SYM " \ SYM (\ SYM )\ SYM&等......

这是我的计划,但它不起作用:

<?php 
 $str = "'this' is Mary! (a dog - not a human)";
 $split = explode(" ",$str);
      foreach($split as $value) {
         $match = array();
         $count = preg_match_all("/\!/|\'/|\-/",$value,$match);
           if ($count != 0)
              $text = "\SYM";
          else
              $text = "\not SYM";
   echo "<br>".$count." ".$value." ".$text;
}
?>

2 个答案:

答案 0 :(得分:1)

您的代码可能就像

一样简单
git pull

正则表达式$ git pull First, rewinding head to replay your work on top of it... Applying: MAF parser, intitial checkin. Passes unit tests [... some 100 lines omitted ...] Applying: Update test to match changed exception Applying: Thank Jeroen for test_QCPSuperimposer.py update Applying: Fix unit test, failed under PyPy 5.6.0 会匹配您的每个特殊字符并将其捕获以供日后使用,但请注意:短划线(<?php $in = "'this' is Mary! (a dog - not a human)"; $out = preg_replace('/([-\'"()*,.:…;?`])/', '\1\\SYM ', $in); echo $out; 应该是字符中的第一个要避免创建范围的类,需要对单引号进行转义(对于PHP)。替换只是将自身的捕获(左侧的第一个捕获括号,/([-'"()*,.:…;?])/)替换为自身,并附加字符串 \ SYM 空白。如果您需要更换更多的空格,可以将替换字符串更改为-或“\1甚至' \1\\SYM '

使用外观的更“复杂”(或优雅或书呆子)的方法看起来几乎相同:

\1 \\SYM '

主要区别在于,它不捕获特殊字符,但匹配 BEHIND 一个。请注意,此处仅匹配 位置 ,此位置(将其视为空字符串)将被您的标记替换 - 实际上只是插入您的标记

两种方法都提供相同的输出:

' \1 \\SYM '

答案 1 :(得分:1)

我认为你想要做的是将一个字符串标记为标点符号(那些SYM个)和由其他字符组成的块(不包括空格,那些not SYM个)。< / p>

使用

$sym_rx = "~(?:([^-'\"()*,.:…;?`\s]+)|([-'\"()*,.:…;?`]))(\s)*~u";
$str = "'this' is Mary! (a dog - not a human)";
echo preg_replace_callback($sym_rx, function ($m) {
    $ins = !empty($m[2]) ? $m[2] . "\\SYM" : $m[1] . "\\not SYM";
    return !empty($m[3]) ? $ins . $m[3] : $ins . " ";
}, $str);
// => '\SYM this\not SYM '\SYM is\not SYM Mary!\not SYM (\SYM a\not SYM dog\not SYM -\SYM not\not SYM a\not SYM human\not SYM )\SYM

请参阅PHP demo