【问题标题】:Regex for line beginning with a character and ending with either of the characters以字符开头并以任一字符结尾的行的正则表达式
【发布时间】:2017-01-05 17:06:25
【问题描述】:

我正在尝试编写一个正则表达式模式,该模式在第一次出现的字符之间抓取字符串,它以“/”开头,可能以“/”或“//”结尾,或者没有。比如——

/test1/code1
/test/code1/code2
/test/code1//code2

以上都应该返回code1。

我尝试了以下正则表达式 -

\/+.*?(\/|\/\/)(.*)

但是,这只在 test1 之后停止并返回所有内容。即/code1//code2。

关于如何确保查找以 / 开头并以 / 或 // 或无结尾的任何建议?

【问题讨论】:

  • 严格的正则表达式不会为您提供工具,但您的编程语言可能会。您使用哪种语言?
  • 你可以使用^\/(.+?)(\/|$)

标签: regex


【解决方案1】:

这个应该做的工作:

/.+?/([^/]+)(?:/|$)

结果在第 1 组。

说明:

/       : a slash
.+?     : one or more any character not greedy
/       : a slash
([^/]+) : one or more any character that is not a slash
(?:/|$) : Non capturing group either a slash or line end

这是一个使用这个正则表达式的 perl 脚本:

#!/usr/bin/perl
use Modern::Perl;
use Data::Dumper;

my $re = qr!/.+?/([^/]+)(?:/|$)!;
while(<DATA>) {
    chomp;
    say (/$re/ ? "OK: \$1=$1\t $_" : "KO: $_");
}

__DATA__
/test1/code1
/test/code1/code2
/test/code1//code2

输出:

OK: $1=code1     /test1/code1
OK: $1=code1     /test/code1/code2
OK: $1=code1     /test/code1//code2

【讨论】:

    猜你喜欢
    • 2019-07-20
    • 2013-08-04
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 2015-04-27
    相关资源
    最近更新 更多