在 php 中拆分以下字符串的正则表达式是什么?

What would be regular expression to split following string in php?

字符串

T1 - X1(1), 7
T2 - C2(-9), -15
T3 - Y2(1), 3
T5 - C2(-1), 100

正则表达式用于 preg_split

$pattern = "/[-,#\n#()]/";
preg_split($pattern, $string);

In above regular expression it is considering the hyphen space same as minus in front of a number.

需要最终结果

数组在 preg_split 和 trim space ["T1","X1","1","7","T2","C2","-9","-15","T3","Y2","1","3","T5","C2","-1","100"]

之后

我可以对正则表达式模式进行哪些更改才能获得所需的最终结果?

你应该跳过负数。这可以用 PCRE 动词来完成:

-\d(*SKIP)(*FAIL)|\s*[-,#\n#()]\s*

PHP 示例:

$string = 'T1 - X1(1), 7
T2 - C2(-9), -15
T3 - Y2(1), 3
T5 - C2(-1), 100';
print_r(preg_split('/-\d(*SKIP)(*FAIL)|\s*[-,#\n#()]\s*/', $string, -1, PREG_SPLIT_NO_EMPTY));
  1. https://3v4l.org/m51qS
  2. https://regex101.com/r/659ocz/1/

您可以匹配空白字符、连字符和空白 s-\s 字符或 | 使用字符 class 匹配要排除的字符 [(),\s] :

\s-\s|[(),\s]

$data = <<<DATA
T1 - X1(1), 7
T2 - C2(-9), -15
T3 - Y2(1), 3
T5 - C2(-1), 100
DATA;

$result = preg_split("~\s-\s|[(),\s]~", $data, -1, PREG_SPLIT_NO_EMPTY);

print_r($result);

Demo