如何使用Perl regexp匹配字符串末尾/开头的空格或环绕的单词? [英] How to match word surronded by spaces OR at the end / beginning of the string using Perl regexp?
问题描述
我想找到与我的正则表达式匹配的序列,如果它们位于由空格包围的字符串中间、结尾或开头,或者是字符串中唯一的内容.
I want to find sequences matching my regexp should they be in the middle of the string surrounded by spaces, in the end or beginning or be the only thing in a string.
示例:让我们假设序列 'qwe45rty'
是我们正在寻找的.我希望能够对所有这些字符串都有积极的态度:
Example:
Let's assume the sequence 'qwe45rty'
is what we are looking for. I want to be able to get positive on all of these strings:
'qwe45rty'
'qwe45rty blabla'
'smth qwe45rty blabla'
'smth qwe45rty'
' qwe45rty '
但这些都不是:
'aaqwe45rty'
'qwe45rtybb'
'aaqwe45rtybb'
我想出的最好的东西是这样的:
Best what I came up with is smth like this:
if ( ($a =~ /\s+$re\s+/) or
($a =~ /^$re\s+/) or
($a =~ /\s+$re$/) or
($a =~ /^$re$/) )
{
# do stuff
}
这不是最好的方法:)
有什么建议吗?
推荐答案
您可以在正则表达式中执行或:
You can do the or inside the regex:
/(^|\s+)qwe45rty(?=\s+|$)/
请注意,第二组是正向前瞻 (?=
),因此它检查是否有空格,但不会消耗它.这样,正则表达式可以匹配字符串的两次连续出现并给出准确的匹配计数.
Note that the second group is a positive lookahead (?=
) so it checks for whitespace, but doesn't consume it. That way the regex can match two consecutive occurrences of the string and give an accurate match count.
这篇关于如何使用Perl regexp匹配字符串末尾/开头的空格或环绕的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!