正则表达式匹配具有以散列开头并以 space 结尾的特殊字符的单词
Regex to match a word with special characters that starts with hash and ends with space
给出的文本:
This is a #tag and this is another #love@irc.oftc.net and more text.
我想匹配以哈希开头并以空白字符结尾的单词(我不想为 #love@irc.oftc.net
指定特定模式)。
我不能使用 lookarounds
并且不想使用 \b
。
我已经尝试了 #.*\b
、#.*\s
,这比我要求的要匹配。我猜 *
也会匹配空格,所以最后的检查被忽略了。
我使用 https://regexr.com/ 进行测试。
除了中间的space,你可以匹配所有字符。
试试这个:
#[^\s]+\s
您可以使用
#\S+
参见regex demo。
详情
#
- #
符号
\S+
- 1个或多个空格以外的字符(也可以写成[^\s]*
,但\S
更短)。
作为一种可能的增强,您仍然可以考虑使用单词和 non-word 边界。例如,当您想避免匹配 abc#tagliketext
或需要避免匹配标签末尾的标点符号时,您可以考虑使用
\B#\S+\b
参见 another regex demo。 \B
non-word 边界如果在#
之前有单词char 将匹配失败,并且\b
将在最右边的non-word 字符之前停止匹配。
给出的文本:
This is a #tag and this is another #love@irc.oftc.net and more text.
我想匹配以哈希开头并以空白字符结尾的单词(我不想为 #love@irc.oftc.net
指定特定模式)。
我不能使用 lookarounds
并且不想使用 \b
。
我已经尝试了 #.*\b
、#.*\s
,这比我要求的要匹配。我猜 *
也会匹配空格,所以最后的检查被忽略了。
我使用 https://regexr.com/ 进行测试。
除了中间的space,你可以匹配所有字符。
试试这个:
#[^\s]+\s
您可以使用
#\S+
参见regex demo。
详情
#
-#
符号\S+
- 1个或多个空格以外的字符(也可以写成[^\s]*
,但\S
更短)。
作为一种可能的增强,您仍然可以考虑使用单词和 non-word 边界。例如,当您想避免匹配 abc#tagliketext
或需要避免匹配标签末尾的标点符号时,您可以考虑使用
\B#\S+\b
参见 another regex demo。 \B
non-word 边界如果在#
之前有单词char 将匹配失败,并且\b
将在最右边的non-word 字符之前停止匹配。