繁体   English   中英

正则表达式捕获提及

[英]regex catching mentions

我需要在没有RT的情况下匹配所有提及。 我试过添加! 否定rt但不起作用。

preg_match( '/\b!rt\s*@([a-zA-Z0-9_]{1,20})/i', $string, $data );

这必须匹配:'你好@user你好吗'。
这不是:'RT @user你好吗'

我不是试图提取用户名或其他东西,我需要知道文本是否有@user没有RT。

有任何想法吗?

! 在正则表达式中没有“否定”。 这符合文字! 你想要的是一个“负面观察”。

/(?<!RT)\s@([a-z0-9]{1,20})/i

(?<!RT)表示“不在”RT“之前。

这将匹配用户名,“RT”不包括在内。

$match = preg_match('/(?<!RT)\s@([a-z0-9]{1,20})/i', $string);

如果$match0 ,则表示字符串为“RT @user ...”。 如果$match不为0 ,则表示该字符串以“RT @user”开头。

演示: http//ideone.com/bOWbu

关于正则表达式的更多信息: http//www.regular-expressions.info/lookaround.html

如果您只想匹配用户名,可以尝试/(?<!RT)(@.*?)(?=\\s)/i

我相信这应该做到:

$string1 = 'hello @user how are you';
preg_match('~\s?(?<!RT) @[a-z0-9]+~i', $string1, $data);
print_r($data);
// array('0' => '@user');

$string2 = 'RT @user how are you';
preg_match('~\s?(?<!RT) @[a-zA-Z0-9]+~', $string2, $data);
print_r($data);
// empty array

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM