【问题标题】:How do i match the character succeeding a particular string?如何匹配特定字符串后面的字符?
【发布时间】:2020-08-16 15:48:32
【问题描述】:

目前我正在使用 perl 正则表达式,作为第一选择,我打算匹配紧接在字符串“Lecture”之后的字符(数字或字母数字),否则在每行没有字符串“Lecture”的情况下匹配最后一个字符。但它似乎不适用于我的用例。我在下面添加我的整个命令

cat 1.txt | perl -ne 'print "$1 \n" while /(?:\w*Lecture)?([^\s]+)$/g;'

注意 - 字符串“Lecture”周围可能没有空格,并且该行可能不一定以 .mp4 结尾

猫 1.txt

54282068 Lecture74- AS 29 Question.mp4   
174424104Lecture 74B - AS 29 Theory.mp4   
Branch Accounts Lecture 105
Lecture05 - Practicals AS 28
Submissions 20.mp4
HW Section 77N

预期输出

74
74B
105
05
20
77N 

我最好想要一个可以直接在 Cli/Console 中运行的解决方案。 (就像我的原始代码一样 - cat 1.txt | perl 代码)。 我不想执行单独的 .pl 文件。

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    您可以使用 alternation | 匹配 Lecture,后跟可选的水平空白字符,或者使用否定的前瞻断言 Lecture 不存在。

    Lecture\h*\K\w+|^(?!.*Lecture).*\h\K[^.\s]+
    
    • Lecture\h* 匹配讲座和可选的水平空白字符
    • \K\w+清除匹配缓冲区并匹配1+字字符
    • |或者
    • ^(?!.*Lecture) 断言 Lecture 不存在
    • .*\h 匹配到最后一个水平空格
    • \K[^.\s]+ 清除匹配缓冲区并匹配除空白字符或点以外的任何字符 1 次以上

    Regex demo

    使用\K 可以在这个例子中得到匹配而不是捕获组。

    例如

    cat 1.txt | perl -ne 'print "$& \n" while /Lecture\h*\K\w+|^(?!.*Lecture).*\h\K[^.\s]+/g;'
    

    输出

    74
    74B
    105
    05
    20
    77N
    

    【讨论】:

      猜你喜欢
      • 2019-08-01
      • 2019-06-05
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多