【问题标题】:Find all alphanumerical strings before a period查找句点前的所有字母数字字符串
【发布时间】:2017-05-05 17:36:10
【问题描述】:

如何检索非字母数字或下划线与句点之间的所有字符串?例如,对于下面的字符串,获取[sources_1st,sources]https://stackoverflow.com/a/10596688/1032531 是一个类似的问题,但似乎对我不起作用。

<?php

function check($pattern,$str)
{
    echo($pattern.'<br>');
    preg_match($pattern, $str, $matches);
    echo('<pre>'.print_r($matches,1).'</pre>');    
}
$str='fullname("protocol",coalesce(sources_1st.protocol,sources.protocol))';
echo($str.'<hr>');

check('/[^.]+\.[^.]+$/',$str);
check('/[\w]\..*$/',$str);
check('/[^\w]\..*$/',$str);
check('/\w\..*$/',$str);
check('/\w+(?=.*\.)$/',$str);
check('/\w+(?=.*\\.)$/',$str);
check('/\b[^ ]+\.$/',$str);
check('/\b[^ ]+\\.$/',$str);
check('/.*?(?=\.)$/',$str);

输出:

fullname("protocol",coalesce(sources_1st.protocol,sources.protocol))
--------------------------------------------------------------------------------
/[^.]+\.[^.]+$/

Array
(
    [0] => protocol,sources.protocol))
)

/[\w]\..*$/

Array
(
    [0] => t.protocol,sources.protocol))
)

/[^\w]\..*$/

Array
(
)

/\w\..*$/

Array
(
    [0] => t.protocol,sources.protocol))
)

/\w+(?=.*\.)$/

Array
(
)

/\w+(?=.*\.)$/

Array
(
)

/\b[^ ]+\.$/

Array
(
)

/\b[^ ]+\.$/

Array
(
)

/.*?(?=\.)$/

Array
(
)

【问题讨论】:

  • 您能给我们举个例子,说明输入的样子和输出的样子吗?
  • @jrn 输入为'fullname("protocol",coalesce(sources_1st.protocol,sources.protocol))',输出为['sources_1st','sources']

标签: php regex preg-match pcre


【解决方案1】:

使用下面的正则表达式,您可以匹配非单词字符和句点之间的单词字符:

\W\K\w+(?=\.)

Live demo

解释:

  1. \W 匹配一个非单词字符
  2. \K扔掉上一场比赛
  3. \w+(?=\.) 不超过句点的任何单词字符

PHP 代码:

preg_match_all('~\W\K\w+(?=\.)~', $str, $matches)

【讨论】:

  • 谢谢雷沃。上一个匹配是每个匹配之前的\W 非单词字符?
  • 不错的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 2022-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多