gpt4 book ai didi

regex - 如何匹配以单个空格分隔的单词与以多个空格分隔的单词

转载 作者:行者123 更新时间:2023-12-01 11:49:34 25 4
gpt4 key购买 nike

我需要将键和值与如下所示的文本分开

Student ID:  0
Department ID =          18432
Name                        XYZ

Subjects:
Computer Architecture
Advanced Network Security 2

在上面的例子中,Student ID、Department ID 和 Name 是键,0,18432, XYZ 是值。键与值通过 :,= 或多个空格分隔。我试过 reg ex 比如

    $line =~ /(([\w\(\)]*\s)*)([=:\s?]?)\s*(\S.*)?$/;
$key = $2;
$colon=$3;
$value = $4;

我面临的问题是识别单词何时用单个空格分隔以及何时用多个空格分隔。

我得到的输出是行是学号:0键是 Student ,值是 ID:0而我想要的键是学生 ID,值为 0。对于像 Subjects: 和 Computer Architecture 这样的行,键应该有 Subjects 和 Computer Architecture。稍后当没有值或冒号时我有逻辑,我将字符串附加到前一个键所以它看起来像 Subjects=Computer Architecture;Advanced Network Security 2

更新:感谢 Ikegami 指出我使用后视运算符。但我似乎仍然无法解决它。

$line=~/^(?: ( [^:=]+ ) (?<!\s\s)\s* [:=]\s*|\s*)(.*)$/x;

所以当我说 (?<!\s\s)\s* [:=]\s*|\s*我的意思是当有两个以上的空间时,消耗所有的空间,当没有两个连续的空间时寻找 : 或 = 并消耗空间。因此,如果您将下行传递给表达式,我不应该得到 $1=Name 和 $2=ABC XYZ 吗?

Name         ABC XYZ

我似乎得到的是键为空,值是名称 ABC XYZ。

最佳答案

如果

Name Eric Brine
Computer Architecture x86

表示

key: Name Eric               value: Brine
key: Computer Architecture value: x86

那么你想要

# Requires 5.10
if (/
^
(?: (?<key> [^:=]+ (?<!\s) ) \s* [:=] \s* (?<val> .* )
| (?<key> .+ (?<!\s) ) \s+ (?<val> \S+ )
)
\s* $
/x) {
my $key = $+{key};
my $val = $+{val};
...
}

if (/
^
(?: ( [^:=]+ (?<!\s) ) \s* [:=] \s* ( .* )
| ( .+ (?<!\s) ) \s+ ( \S+ )
)
\s*
( .* )
/x) {
my ($key,$val) = defined($1) ? ($1,$2) : ($3,$4);
...
}

如果

Name Eric Brine
Computer Architecture x86

表示

key: Name       value: Eric Brine
key: Computer value: Architecture x86

那么你想要

# Requires 5.10
if (/
^
(?: (?<key> [^:=]+ (?<!\s) ) \s* [:=]
| (?<key> \S+ ) \s
)
\s*
(?<val> .* )
/x) {
my $key = $+{key};
my $val = $+{val};
...
}

if (/
^
(?: ( [^:=]+ (?<!\s) ) \s* [:=]
| ( \S+ ) \s
)
\s*
( .* )
/x) {
my $key = defined($1) ? $1 : $2;
my $val = $3;
...
}

请注意,您可以删除所有空格和换行符。例如,最后一个片段可以写成:

if (/^(?:([^:=]+(?<!\s))\s*[:=]|(\S+)\s)\s*(.*)/) {
my $key = defined($1) ? $1 : $2;
my $val = $3;
...
}

关于regex - 如何匹配以单个空格分隔的单词与以多个空格分隔的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12714827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com