Perl:我如何匹配这样的模式?

时间:2022-09-13 12:15:48

Say there are two words like: googleweb.us and google.us

比如说有两个词:googleweb.us和google.us

This is one way I worked out to match these in a single regex, but it looks ugly.

这是我在单个正则表达式中匹配这些的一种方法,但它看起来很难看。

/(google|espn|foxtel)\w*[web\.\w+|\.\w+]/

I only want to cover both of the two cases when "web" exists or not. How could the pattern could be improved?

当“web”存在与否时,我只想涵盖这两种情况。怎么可以改善模式?

2 个解决方案

#1


2  

This will allow "web" to be optional for just google:

这将允许“web”对于谷歌来说是可选的:

/(google(web)?|espn|foxtel)\.\w+/

This will allow "web" to be optional for any of the domains:

这将允许“web”对任何域都是可选的:

/(google|espn|foxtel)(web)?\.\w+/

#2


1  

You need to revise your 'character class'. The material in square brackets is treated as a character class, and isn't what you had in mind.

你需要修改你的“角色类”。方括号中的材料被视为字符类,而不是您的想法。

A regex that would match what you ask about in words ('googleweb.us' and 'google.us') is:

正如你所要求的那样('googleweb.us'和'google.us')匹配的正则表达式是:

/^(google)(web)?\.us$/

When you've defined what else you want it to match, people can refine the regex.

当你定义了你想要匹配的其他内容时,人们可以优化正则表达式。

#1


2  

This will allow "web" to be optional for just google:

这将允许“web”对于谷歌来说是可选的:

/(google(web)?|espn|foxtel)\.\w+/

This will allow "web" to be optional for any of the domains:

这将允许“web”对任何域都是可选的:

/(google|espn|foxtel)(web)?\.\w+/

#2


1  

You need to revise your 'character class'. The material in square brackets is treated as a character class, and isn't what you had in mind.

你需要修改你的“角色类”。方括号中的材料被视为字符类,而不是您的想法。

A regex that would match what you ask about in words ('googleweb.us' and 'google.us') is:

正如你所要求的那样('googleweb.us'和'google.us')匹配的正则表达式是:

/^(google)(web)?\.us$/

When you've defined what else you want it to match, people can refine the regex.

当你定义了你想要匹配的其他内容时,人们可以优化正则表达式。