簡體   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