preg_match_all使用特殊字符拆分条件表达式



我有这种格式的数据:

Randomtext1(#random2#, #random4#) == 1 && Randomtext2 (ran dom) != 2 || #Randomtext3# > 3 && Randomtext4 (random5,random7,random8) || Randomtext5  (Randomtext4 (random5,random7,random8), random10) < Randomtext11()

有了这个:

preg_match_all("~w+(?:s*(([^()]*+(?:(?1)[^()]*)*+)))?~", $expression, $matches);

我获得:

0 => 'Randomtext1(#random2#, #random4#)',
1 => '1',
2 => 'Randomtext2 (ran dom)',
3 => '2',
4 => 'Randomtext3',
5 => '3',
6 => 'Randomtext4 (random5,random7,random8)',
7 => 'Randomtext5  (Randomtext4 (random5,random7,random8), random10)',
8 => 'Randomtext11()',

但我想要:

0 => 'Randomtext1(#random2#, #random4#)'
1 => '1'
2 => 'Randomtext2 (ran dom)'
3 => '2'
4 => '#Randomtext3#'
5 => '3',
6 => 'Randomtext4 (random5,random7,random8)',
7 => 'Randomtext5  (Randomtext4 (random5,random7,random8), random10)',
8 => 'Randomtext11()',

的问题,我失去了元素 4 的#

有什么想法吗?

w0-9a-zA-Z_ * 您还需要允许#,您可以使用更改或字符类。

[#w]+

(?:#|w)+

完整示例:

[#w]+(?:s*(([^()]*+(?:(?1)[^()]*)*+)))?

演示:https://3v4l.org/75eGQ

正则表达式演示:https://regex101.com/r/1PYvpO/1/

\w 代表 "单词字符"。它始终与 ASCII 字符 [A-Za-z0-9_] 匹配。请注意包含下划线和数字。在大多数支持 Unicode 的风格中,\w 包含来自其他脚本的许多字符。关于实际包含哪些字符存在很多不一致之处。通常包括字母脚本和表意文字中的字母和数字。除下划线和非数字符号之外的连接器标点符号可能包含,也可能不包含。XML Schema 和 XPath 甚至包含 \w 中的所有符号。

*https://www.regular-expressions.info/shorthand.html

我想我会在preg_split()中使用这种更简单的模式。 对眼睛来说要容易得多。

代码: (PHP 演示) (模式演示)

$string='Randomtext1(#random2#, #random4#) == 1 && Randomtext2 (ran dom) != 2 || #Randomtext3# > 3 && Randomtext4 (random5,random7,random8) || Randomtext5  (Randomtext4 (random5,random7,random8), random10) < Randomtext11()';
var_export(preg_split('/ [=!&|<>]{1,2} /',$string));

输出:

array (
  0 => 'Randomtext1(#random2#, #random4#)',
  1 => '1',
  2 => 'Randomtext2 (ran dom)',
  3 => '2',
  4 => '#Randomtext3#',
  5 => '3',
  6 => 'Randomtext4 (random5,random7,random8)',
  7 => 'Randomtext5  (Randomtext4 (random5,random7,random8), random10)',
  8 => 'Randomtext11()',
)

这将匹配并拆分==&&!=>||<上的字符串(分隔值周围有一个前导空格和一个尾随空格 - 在格式化文本中很难看到)

最新更新