匹配以@开头的单词

时间:2019-12-23 09:18:30

标签: regex

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

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

因此,在这种情况下,我仅将一个单词-@as与该单词前面的空格匹配。

但是我也需要数学@refactoringGuru

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

我该怎么做?

2 个答案:

答案 0 :(得分:1)

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

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

Demo

正则表达式的解释:

(?<!\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

答案 1 :(得分:0)

您可以使用

(?<=^|\s)@\S+

请参见a demo on regex101.com