[英]Making a capturing group optional in a regex
I have an automatically-generated email that I'm trying to parse out into fields for import into an application. 我有一个自动生成的电子邮件,试图将其解析为字段以导入到应用程序中。 I have a working regex for if all of the fields are present.
如果所有字段都存在,我可以使用正则表达式。 However, this won't always be the case.
但是,情况并非总是如此。 Specifically, the phone number will sometimes be missing.
具体来说,电话号码有时会丢失。
$regex = '/Bill\sTo:\s+([A-Za-z]+\s[A-Za-z]+)\s.+[A-Z]{2}\s(\d{5})\s.*\s((?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4})\s+([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})\s+Ship\sTo:/s';
// ^ Name ^ ^State ^ ^ Zip ^ ^ Phone Number ^ ^ Email ^
if (preg_match($regex, $content, $matches)) {
$import = new ImportedEmail;
$import->name = $matches[1];
$import->zip = $matches[2];
$import->phone = $matches[3];
$import->email = $matches[4];
// ...more processing code follows.
}
How can I get it to extract a phone number when it's present, but drop a NULL into $import->phone
otherwise? 我如何获取它来提取一个存在的电话号码,否则将一个NULL放入
$import->phone
呢?
Note that "State" is in the regex just to help zero in on the location of the zip code. 请注意,“ State”位于正则表达式中,只是为了帮助使邮政编码位置为零。
You can give the capture group a name (?P<name> ...)
and make it optional using the ?
您可以给捕获组起一个名字
(?P<name> ...)
并使用?
使其可选?
. 。
I have prepared a simplified example. 我准备了一个简化的例子。 Let's say you have a string like:
假设您有一个类似的字符串:
name [age (optional)] message:
You can parse it with the following regex: 您可以使用以下正则表达式进行解析:
// Jon is 37 years old
$str1 = 'jon 37 hello world';
// Jane does not tell about her age ;)
$str2 = 'jane foo bar';
preg_match('/(?P<name>[a-z]+ )?(?P<age>[0-9]+ )?(?P<message>.*)/', $str1, $m);
echo $m['name'] . PHP_EOL;
echo $m['age'] . PHP_EOL;
echo $m['message'] . PHP_EOL;
preg_match('/(?P<name>[a-z]+ )?(?P<age>[0-9]+ )?(?P<message>.*)/', $str2, $m);
echo $m['name'] . PHP_EOL;
echo $m['age'] . PHP_EOL; // index exists but is now empty
echo $m['message'] . PHP_EOL;
Put a ? 放一个? directly after your phone number capturing group.
直接在您的电话号码捕获组之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.