首页 > 解决方案 > 匹配以@开头的单词

问题描述

我有下一个模式(^| )@[^@ ]+($|)

我有下一个字符串:cdc@cd csd@ @as @refactoringGuru @ @as@refactoringGuru.

所以,在这种情况下,我只匹配一个单词——@as单词前有空格。

但我也需要数学@refactoringGuru

所以,我需要下一个输出 -@as @refactoringGuru单词前没有空格。我不匹配@as@refactoringGuru

我怎么能做到这一点?

标签: regex

解决方案


您可以尝试使用否定的lookbehind(?<!\S)@来匹配@单词开头的符号:

(?<!\S)@\w+(?!\S)

演示

正则表达式的解释:

(?<!\S)   assert that what precedes is either whitespace or the start of the input
@         match an @ symbol
\w+       match one or more word characters
(?!\S)    assert that what follows is either whitespace or the end of the input

推荐阅读