regex - Perl 正则表达式 : How to grab the part that is the same

标签 regex perl pcre

我正在为一些游戏创建天梯系统,但遇到了有关部落基础系统的问题。你看,每个加入的玩家都会被解析并放入玩家表中。像这样:

chelsea | gordon 
chelsea | jim
chelsea | brad

或者...

CLANTAG|> jenna
CLANTAG|> jackson
CLANTAG|> irene 

所以,我想要的是:我想要捕获 CLANTAG,它位于同一位置,并且该团队中每个球员的名字都相同。但是,分隔符可以是任何内容,从空格到什么都没有(部落玩家 1、部落玩家 2 或部落玩家 1、部落玩家 2)。

关于如何做到这一点有什么想法吗?

提前致谢。

最佳答案

这是一个镜头:

use strict;
use warnings;

my($strip) = shift || 0;

print FindTeamName("TEAMJimBob", "TEAMJoeBob", "TEAMBillyBob"), "\n";
print FindTeamName("TEAM|JimBob", "TEAM|JoeBob", "TEAM|BillyBob"), "\n";
print FindTeamName("TEAM | JimBob", "TEAM | JoeBob", "TEAM | BillyBob"), "\n";
print FindTeamName("TEAMJimBob", "TEAM|JoeBob", "TEAM - BillyBob"), "\n";

sub FindTeamName
{
    my(@players) = @_;

    my($team) = shift;
    foreach my $player (@players) {
        $team = FindCommonString($team, $player);
    }

    $team =~ s{\W+$}{} if $strip;

    $team;
}

sub FindCommonString
{
    my($str1, $str2) = @_;

    my(@arr1) = split(//, $str1);
    my(@arr2) = split(//, $str2);

    my($common) = "";

    while (@arr1 && @arr2) {
        my($letter1) = shift(@arr1);
        my($letter2) = shift(@arr2);

        if ($letter1 eq $letter2) {
            $common .= $letter1;
        }
        else {
            last;
        }
    }

    $common;
}

给出以下内容:

C:\temp>perl test.pl
TEAM
TEAM|
TEAM |
TEAM

C:\temp>perl test.pl 1
TEAM
TEAM
TEAM
TEAM

C:\temp>

关于regex - Perl 正则表达式 : How to grab the part that is the same,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/572160/

相关文章:

Python正则表达式: making multiple different substitutions in a single pass using Groups

sql - 甲骨文 SQL : Regexp_substr

python - 正则表达式将 IP 与 jsonschema 中的掩码进行匹配

javascript - Javascript 中十进制输入的正则表达式,小数点前有 1 到 3 位数字,小数点后有 1 到 3 位数字

perl - 区分perl中的字符串和数字参数

Perl 应用程序安装

c++ - pcre 不能支持多个子组

c++ - 如何从 C++ 调用 perl?

php - preg_match_all html 标签,双引号或单引号中的标签除外

c++ - 如何用PCRE2实现/e修饰符?