简体   繁体   English

正则表达式查找以特定字符开头的特定单词

[英]Regex to find specific word starting with a specific char

Using Regex, I need to find a word within a string that starts with specific char. 使用Regex,我需要在以特定char开头的字符串中找到一个单词。 The word must be alphanumeric, but may contain underscore (_) within the word. 该单词必须是字母数字,但单词中可以包含下划线(_)。 underscore at the beginning and end of the word is not acceptable. 在单词的开头和结尾都必须使用下划线。

For example I have the following string. 例如,我有以下字符串。

@word1 Message @@ message @ message @word2_ message @word#3 @_word4 mesagge @word_5 @ word1消息@@消息@消息@ word2_消息@ word#3 @ _word4消息@ word_5

The result should be: 结果应为:

@word1 @word_5 @ word1 @ word_5

Thanks. 谢谢。

Use regex pattern 使用正则表达式模式

(?:^|(?<=\s))@(?!_)\w+(?<!_)(?:(?=\s)|$)

or 要么

(?:^|(?<=\W))@(?!_)\w+(?<!_)(?:(?=\W)|$)

depends what you need/want to have infront/behind... 取决于您需要/想要在前/后...

For example if @word1 in @word_5 @word1. @word#2 @word*3 例如,如果@word1 @word_5 @word1. @word#2 @word*3 @word_5 @word1. @word#2 @word*3 should match, considering dot . 考虑到dot, @word_5 @word1. @word#2 @word*3应该匹配. as separator or end of sentence. 作为分隔符或句子结尾。

This will work - the bounds (lines 1 and 3) are fairly heavy because \\b , the word boundary, won't work here since you don't want to match "@word#3", and the "#" character after "d" triggers a word boundary. 这将起作用-边界(第1行和第3行)相当沉重,因为\\b (单词边界)在这里不起作用,因为您不想匹配“ @ word#3”,而后面的“#”字符“ d”触发单词边界。

(?<=\s|^)
    @(?!_)\w+(?<!_)
(?=\s|$)

This Regex will do it! 这个正则表达式将做到这一点!

(?<=(^|\s))@([a-zA-Z0-9]{1}\w*[a-zA-Z0-9]|[a-zA-Z0-9]{1})(?=(\s|$))

It also matches single letter 它也匹配单个字母

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

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