正则表达式php在不同的组中从字符串中分离出精确的单词
我已经尝试了我所知道的一切,但仍然不知道如何解决此问题: 我有一个字符串:正则表达式php在不同的组中从字符串中分离出精确的单词,php,regex,word,Php,Regex,Word,我已经尝试了我所知道的一切,但仍然不知道如何解决此问题: 我有一个字符串: “--包括--在销售价格中:5%增值税10.00美元包装费2%通知费” “--不包括在销售价格中:35.00美元快递费2%通知费” 我想知道税是“包括”还是“不包括”,费用是“%还是“货币” 问题在于,当货币“usd”附加到税号“vat usd”时,它没有检测到货币“usd” 如何将货币与不同组中的税务名称区分开来 以下是我所做的 (--excluded--|--included--|--not included--
“--包括--在销售价格中:5%增值税10.00美元包装费2%通知费”
“--不包括在销售价格中:35.00美元快递费2%通知费”
(--excluded--|--included--|--not included--)([a-z ]*)?:?(usd | aed | mad | € | us\$ )?([ \. 0-9 ]*)(%)?([a-z A-z ?]*) (aed|mad|€|us\$)*((aed|mad|€|us\$)+)?([\. 0-9 ]*)(%)?([a-z A-z]*)(.*)?
这是我得到的
(--excluded--|--included--|--not included--)([a-z ]*)?:?(usd | aed | mad | € | us\$ )?([ \. 0-9 ]*)(%)?([a-z A-z ?]*) (aed|mad|€|us\$)*((aed|mad|€|us\$)+)?([\. 0-9 ]*)(%)?([a-z A-z]*)(.*)?
匹配1
完全匹配0-83--包括在销售价格中:5%增值税10.00美元包装费2%通知费
第一组。0-12--包括在内--
第2组。销售价格中的12-29
第4组。30-33 5
第5组。33-34 %
第6组。34-42美元增值税
第10组。43-49 10.00
第12组。49-64包装费
第13组。64-82 2%通知费
这就是我想要的
匹配1
完全匹配0-83--包括在销售价格中:5%增值税10.00美元包装费2%通知费
第一组。0-12--包括在内--
第2组。销售价格中的12-29
第4组。30-33 5
第5组。33-34 %
第6组。34-38增值税
第7组。38-42美元
第10组。43-49 10.00
第12组。49-64包装费
第13组。64-82 2%通知费
以下是解决方案:
$s = "--included-- in product price: breakfast --excluded--: 5 % vat aed 10.00 destination fee per night 2 % municipality fee 3.5 % packaging fee 10 % warranty service charge";
$results = [];
if (preg_match_all('~(--(?:(?:not )?in|ex)cluded--)(?:\s+([a-zA-Z ]+))?:+\s*((?:(?!--(?:(?:not )?in|ex)cluded--).)*)~su', $s, $m, PREG_SET_ORDER, 0)) {
foreach ($m as $v) {
$lastline=array_pop($v); // Remove last item //print_r($details);
if (preg_match_all('~(?:(\b(?:usd|aed|mad|usd)\b|\B€|\bus\$)\s*)?\d+(?:\.\d+)?(?:(?!(?1))\D)*~ui', $lastline, $details)) {
$results[] = array_merge($v, $details[0]);
} else {
$results[] = $v;
}
}
}
print_r($results);
看
注:
第一个正则表达式提取需要解析的每个匹配项。看见这意味着:
-第1组:较短版本的(-(?:(?:不)?包括在内--
:(-排除--include--not include--not include--
,--排除--
或--包括--
--不包括--
-可选序列:1+空格,然后分组2:1+ASCII字母或空格(?:\s+([a-zA-Z]+)?
-1个或多个冒号:+
-0+空格\s*
-第3组:任何字符,0+次,尽可能多,不启动三个字符序列中的任何一个:((?:(?!-(?:(?:不)?在| ex)中包括-)*)
,--排除--
,--包括--
--不包括--
-可选的(?:(\b(?:usd | aed | mad | usd)\b | \b€| \bus\$)\s*)?
-第1组:(\b(?:usd | aed | mad | usd)\b | \b€| \bus\$)
-\b(?:usd | aed | mad | usd)\b
,usd
,aed
或mad
作为整句话usd
-\B€
前面没有字符€
-\bus\$
前面没有字符us$
-0+空格\s*
\d+
-可选的(?:\。\d+)
和1+数字序列
-任何非数字字符,尽可能多地出现0次或更多次,与组1中的模式不同(?:(?!(?1))\D)*