返回前8个字符的正则表达式匹配

时间:2014-08-14 21:58:28

标签: regex

我正在尝试匹配域的前8个字符。目前我的规则是:

必须只是第8个

如果不存在8个字符,请抓住.tld 之前的每个字符

我的正则表达式目前如此:^(www\.)?(?<domain>.+)$

就像google.com

一样

在我的情况下,我会抓住google

thisislongerthen8characterslong.com的情况下,我想返回thisislo

2 个答案:

答案 0 :(得分:4)

^(?:www\.)?(.{1,8}).*\.[A-Za-z0-9]+$

匹配

google.com                        : google
thisisanenormousdomain.co.uk      : thisisan
google.co.uk                      : google.c
www.google.com                    : google
www.thisisanenormousdomain.co.uk  : thisisan

技术细节:

^(?:www\.)?(.{1,8}).*\.[A-Za-z0-9]+$
│└────┬───┘└───┬──┘└┬─┘└─────┬─────┘
│     │        │    │        └ 5. Match TLD (e.g. com, uk, org, net, etc)
│     │        │    └ 4. Match anything after the first eight characters, up until the last '.' in the url.
│     │        └ 3. Capture between one and eight characters inside a match group.
│     └ 2. Match an optional www. prefix. Do not add to match groups.
└ 1. Find the start of the string.

试一试:http://rubular.com/r/wLX2C9jg26

答案 1 :(得分:0)

您需要在.上使用量词:

^(?:www\.)?(?<domain>.{0,8}).*\..{2,3}$

Regex101示例