Regex 句子和/或字符范围内的正则表达式匹配
我试图找到一个跟在已知“锚”字后面的术语。到目前为止,我已经做了类似于以下内容的工作:Regex 句子和/或字符范围内的正则表达式匹配,regex,wildcard,Regex,Wildcard,我试图找到一个跟在已知“锚”字后面的术语。到目前为止,我已经做了类似于以下内容的工作: Weight(:( )?)(\d{1,2} lbs|pounds|ounces|kilos) 那么一条像 体重:10磅 向我返回“10磅”(事实上,我用名称组标识数字和度量值,但我离题了)。我发现在某些情况下,事先可能会有一些文字 重量:高达10磅 或 重量:可高达或不超过10磅 我希望在这两者之间插入一些正则表达式,可以允许一个合理的随机字符数,也可以允许任何带有句点或换行符的随机字符数。我
Weight(:( )?)(\d{1,2} lbs|pounds|ounces|kilos)
那么一条像
- 体重:10磅
- 重量:高达10磅
- 重量:可高达或不超过10磅
Weight(:( )?)(.*?)(?P<WEIGHT>(\d{1,2} lbs|pounds|ounces|kilos))[.\n]
返回
- 重量[14-24]
250磅
/weight.*?\s(?P<number>\d+)\s+(?P<name>(?:lb|pound|ounce|kilo)s?)(?:$|\s|\pP)/i
/weight.*\s(?P\d+)\s+(?P(?:磅|盎司|千克)s?($)\s |\pP)/i
- “重量”后跟任何东西(不贪婪)
- 周围有空格的数字
- 以字符串结尾的名称、空格或标点符号
$regex = '/weight.*?\s(?P<number>\d+)\s+(?P<name>(?:lb|pound|ounce|kilo)s?)(?:$|\s|\pP)/i';
$tests = array(
'Weight: 65 lbs',
'Weight: up to 1 kilo',
'Weight: can be up to or not more then 10 lbs.',
'Weight can be 250 ounces',
'His weight is around 75 kilos',
'He is very heavy -- about 190 kilos!',
);
foreach ($tests as $test) {
preg_match($regex, $test, $match);
if (empty($match)) {
echo "No match (\"$test\")<br>";
} else {
echo "Match: {$match['number']} {$match['name']} (\"$test\")<br>";
}
}
$regex='/weight.*?\s(?P\d+)\s+(?P(?:磅|磅|盎司|千克)s?($)\s | \pP)/i';
$tests=数组(
“重量:65磅”,
“重量:不超过1公斤”,
“重量:可高达或不超过10磅。”,
“重量可以是250盎司”,
“他的体重在75公斤左右”,
“他很重——大约190公斤!”,
);
foreach($tests作为$test){
预匹配($regex,$test,$match);
if(空($match)){
回显“不匹配(\“$test\”)
”;
}否则{
echo“Match:{$Match['number']}{$Match['name']}(\“$test\”)
”;
}
}
是否要排除非数字字符,以便权重可能在250左右
只捕获权重
和250
?如果是这样,这与您的标准有何不符:Weight[^.\n\r\d]+(\d+(?:磅|公斤))
您可以添加负回溯(?在数字组之前,如下所示:Weight[^.]{1,30}(?P(?@OnlineCop不,事实上,这只是一个更复杂的正则表达式的示例,其中也包含带有非数字字符的模式。不过,在我可以调整的地方,上面的工作已经足够好了you@UlugbekUmirov我认为,我需要的正是背后的消极的一面(每天学习新的东西,只需进入regex一周)它就像一个符咒。
/weight.*?\s(?P<number>\d+)\s+(?P<name>(?:lb|pound|ounce|kilo)s?)(?:$|\s|\pP)/i
$regex = '/weight.*?\s(?P<number>\d+)\s+(?P<name>(?:lb|pound|ounce|kilo)s?)(?:$|\s|\pP)/i';
$tests = array(
'Weight: 65 lbs',
'Weight: up to 1 kilo',
'Weight: can be up to or not more then 10 lbs.',
'Weight can be 250 ounces',
'His weight is around 75 kilos',
'He is very heavy -- about 190 kilos!',
);
foreach ($tests as $test) {
preg_match($regex, $test, $match);
if (empty($match)) {
echo "No match (\"$test\")<br>";
} else {
echo "Match: {$match['number']} {$match['name']} (\"$test\")<br>";
}
}