如何编写正则表达式以在文本格式中没有换行的字符串中的冒号后查找空 space?
How to write regex to find empty space after colon in string with no new line in text format?
I am creating one regex to find words after colon in my pdftotext
. i
am getting data like:
I am using this xpdf to convert uploaded pdf by user into text format.
$text1 = (new Pdf('C:\xpdf-tools-win-4.00\bin64\pdftotext.exe'))
->setPdf('path')
->setOptions(['layout', 'layout'])
->text();
$string = $text1;
$regex = '/(?<=: ).+/';
preg_match_all($regex, $string, $matches);
在->setPdf('path')
路径中将是上传文件的路径。
我得到以下数据:
Full Name: XYZ
Nationality: Indian
Date of Birth: 1/1/1988
Permanent Residence Address:
在我上面的数据中你可以看到居住地址是空的。
我正在写一个正则表达式来查找冒号后的单词。
但在 $matches 上它的结果只有:
当前O/P:
Array
(
[0] => Array
(
[0] => xyz
[1] => Indian
[2] => 1/1/1988
)
)
如果正则表达式在冒号后发现空格或空值,则跳过:
我也希望数组中的结果为空值。
预期 O/P:
Array
(
[0] => Array
(
[0] => xyz
[1] => Indian
[2] => 1/1/1988
[3] =>
)
)
注意:OP在给出了几个答案后改变了他的问题。
这是对原问题的回答。
这是一种解决方案,使用 preg_match_all
。我们可以尝试匹配以下模式:
(?<=:)[ ]*(\S*(?:[ ]+\S+)*)
这匹配冒号后的任意数量的空格,空格后跟任意数量的单词。我们从 preg_match_all
访问输出数组的第一个索引,因为我们只想要在第一个捕获组中捕获的内容。
$input = "name: xyz\naddress: db,123,eng.\nage:\ngender: male\nother: hello world goodbye";
preg_match_all ("/(?<=:)[ ]*(\S*(?:[ ]+\S+)*)$/m", $input, $array);
print_r($array[1]);
Array
(
[0] => xyz
[1] => db,123,eng.
[2] =>
[3] => male
[4] => hello world goodbye
)
使用捕获组是一个很好的方法,因为捕获组理论上应该出现在输出数组中,即使没有捕获项。
您的代码 $regex = '/\b: \s*'\K[\w-]+/i';,在 \K 之前结束。您有 3 个引号,前 2 个引号捕获了模式。
无论如何,你可以做的是使用组来捕获冒号后的输出,包括空格:
$regex = "^.+: (\s?.*)" should work.
I am creating one regex to find words after colon in my
pdftotext
. i am getting data like: I am using this xpdf to convert uploaded pdf by user into text format.
$text1 = (new Pdf('C:\xpdf-tools-win-4.00\bin64\pdftotext.exe'))
->setPdf('path')
->setOptions(['layout', 'layout'])
->text();
$string = $text1;
$regex = '/(?<=: ).+/';
preg_match_all($regex, $string, $matches);
在->setPdf('path')
路径中将是上传文件的路径。
我得到以下数据:
Full Name: XYZ
Nationality: Indian
Date of Birth: 1/1/1988
Permanent Residence Address:
在我上面的数据中你可以看到居住地址是空的。 我正在写一个正则表达式来查找冒号后的单词。
但在 $matches 上它的结果只有: 当前O/P:
Array
(
[0] => Array
(
[0] => xyz
[1] => Indian
[2] => 1/1/1988
)
)
如果正则表达式在冒号后发现空格或空值,则跳过: 我也希望数组中的结果为空值。 预期 O/P:
Array
(
[0] => Array
(
[0] => xyz
[1] => Indian
[2] => 1/1/1988
[3] =>
)
)
注意:OP在给出了几个答案后改变了他的问题。 这是对原问题的回答。
这是一种解决方案,使用 preg_match_all
。我们可以尝试匹配以下模式:
(?<=:)[ ]*(\S*(?:[ ]+\S+)*)
这匹配冒号后的任意数量的空格,空格后跟任意数量的单词。我们从 preg_match_all
访问输出数组的第一个索引,因为我们只想要在第一个捕获组中捕获的内容。
$input = "name: xyz\naddress: db,123,eng.\nage:\ngender: male\nother: hello world goodbye";
preg_match_all ("/(?<=:)[ ]*(\S*(?:[ ]+\S+)*)$/m", $input, $array);
print_r($array[1]);
Array
(
[0] => xyz
[1] => db,123,eng.
[2] =>
[3] => male
[4] => hello world goodbye
)
使用捕获组是一个很好的方法,因为捕获组理论上应该出现在输出数组中,即使没有捕获项。
您的代码 $regex = '/\b: \s*'\K[\w-]+/i';,在 \K 之前结束。您有 3 个引号,前 2 个引号捕获了模式。
无论如何,你可以做的是使用组来捕获冒号后的输出,包括空格:
$regex = "^.+: (\s?.*)" should work.