简体   繁体   English

这个正则表达式/ ^([^-] *)(-*。)有什么问题?/?

[英]What's wrong with this regex /^([^-]*)( - *.)?/?

Consider this: 考虑一下:

my @str = ("Farbkeil","L 0AA61 Rec","L 0AA61 Rec - 150 dpi",,"L 0AA61 Rec - 400 dpi");
for my $s (@str) {
#   my ($m) = ($s =~ /^([^-]*)(?=-)/);
#   my ($m) = ($s =~ /^([^-]*) (?=-)/);
    my ($m) = ($s =~ /^([^-]*)( - *.)?/);
    print "$s => -$m-\n";
}

It produces this output 它产生这个输出

Farbkeil => -Farbkeil-
L 0AA61 Rec => -L 0AA61 Rec-
L 0AA61 Rec - 150 dpi => -L 0AA61 Rec -
L 0AA61 Rec - 400 dpi => -L 0AA61 Rec -

What I want is to get rid of the space before the optional "-", so that it looks like 我想要的是除去可选的“-”之前的空格,以便它看起来像

Farbkeil => -Farbkeil-
L 0AA61 Rec => -L 0AA61 Rec-
L 0AA61 Rec - 150 dpi => -L 0AA61 Rec-
L 0AA61 Rec - 400 dpi => -L 0AA61 Rec-

I've tried the above regexes, the last one is the closest but not quite. 我已经尝试了上面的正则表达式,最后一个是最接近的,但还不完全是。 Guessing didn't work either, surprisingly... Of course I could just trim the result, but there must be a more elegant way? 令人惊讶的是,猜测也没有用……我当然可以调整结果,但是必须有更优雅的方法吗?

Any ideas? 有任何想法吗?

You can use this regex for match: 您可以使用此正则表达式进行匹配:

/^([^-]+)(?=\s-|$)/

RegEx Demo 正则演示

(?=\\s-|$) is a lookahead that makes sure first part ([^-]+) is always followed by a space + hyphen OR end of input . (?=\\s-|$)是一个超前查询,可确保第一部分([^-]+)始终后跟空格+连字符input的结尾

And another one. 还有一个。 Just because it requires only one small change to your initial Regex. 仅仅因为它只需要对初始Regex进行一点小改动。 (note the \\b outside the round brackets). (请注意\\b在圆括号外)。 \\b is for word boundary. \\b用于单词边界。

my @str = ("Farbkeil","L 0AA61 Rec","L 0AA61 Rec - 150 dpi",,"L 0AA61 Rec - 400 dpi");
for my $s (@str) {
    my ($m) = ($s =~ /^([^-]*)\b(-)?/);
    print "$s => -$m-\n";
}

As for why your Regex failed: 至于为什么您的正则表达式失败:

([^-]*) greedily matches everything that is not a - . ([^-]*)贪婪地匹配不是- Thus it always matches the trailing space if it's there. 因此,如果存在,它将始终匹配尾随空间。 The \\b forces a stop and can match amongst others a space or end of line. \\b强制停止,并且可以匹配空格或行尾。

I'd just remove / - .*/ 我只想删除/ - .*/

for my $s (@str) {
    (my $m = $s) =~ s/ - .*//;
    print "$s => [$m]\n";
}

In more recent Perls, you can use /r : 在最新的Perls中,可以使用/r

my $m = $s =~ s/ - .*//r;

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

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