繁体   English   中英

Perl 正则表达式匹配出现单冒号

[英]Perl Regex Match Occurrence of Single Colon

我正在尝试使用以下标准正则表达式匹配模式:

我想匹配一个在整个字符串中只出现一次的字符串。 然后我想捕获单个冒号之前的部分。

有效字符串示例:

JohnP: random text here
BobF::student: random text here (this is valid because there's only ONE occurrence of a single colon. the other is a double colon)
Paris: random text here::student (valid for the same reason as above)

无效字符串示例:

JohnP: student: random text here
BobF::student: random text here: more

我不知道如何进行这样的正则表达式匹配。 在有效字符串的情况下,我要返回的组是:

JohnP
BobF::student
Paris

我将不胜感激! 我试过$string =~ ^[^:]+:\s* ,但只匹配第一个冒号。

您可以使用此正则表达式:

^((?:::|[^:])*+):(?!.*(?<!:):(?!:))

它查找一定数量的冒号对或非冒号字符后跟一个冒号,使用所有格量词 ( *+ ) 来防止在诸如Bill:: xyz之类的字符串中通过双冒号进行部分匹配。 这些字符被捕获在第 1 组中。然后使用否定的前瞻断言来检查字符串中是否没有更多的单个冒号。

正则表达式 101 上的演示

也许正则表达式可以采用以下形式:匹配直到:前面没有:并且后面没有:

注意:代码以缩写形式编写

use strict;
use warnings;
use feature 'say';

my $re = qr/^(.+)(?<!:):(?!:)/;

/$re/ && say $1 for <DATA>;

__DATA__
JohnP: random text here
BobF::student: random text here (this is valid because there's only ONE occurrence of a single colon. the other is a double colon)
Paris: random text here::student (valid for the same reason as above)

Output

JohnP
BobF::student
Paris

暂无
暂无

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

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