regex - 相当具体的 Perl 正则表达式

标签 regex perl

我正在寻找一种与之匹配的模式:

(单词单词单词单词) | 1234.5678% | (1234)

我想将(words、words、words)保留为$1,将(1234)保留为$2强>

输入文件如下所示:

Header Crap | More Header Crap|Header Crap | More Header Crap|(words words words words) | 1234.5678% | (1234) | (words words words words) | 1234.5678%        |   (1234)(words words words words) | 1234.5678% | (1234) | (words words words words) |   1234.5678% | (1234)(words words words words) | 1234.5678% | (1234) | (words words words words) | 1234.5678% | (1234) | (words words words words) | 1234.5678% | (1234) | (words words words words) | 1234.5678% | (1234)

我认为这个问题与输入有关。它作为一个大 blob 出现(即 $_ 是一大串数据,需要对其进行解析以查找匹配项)

我尝试过的事情:

while ($_ =~ /(.*)\|{1}\d*?\.{1}\d*?%{1}\|{1}(\d*)/ {
do stuff with $1 and $2
}

以及

@matches = $_ =~ /(.*)\|{1}\d*?\.{1}\d*?%{1}\|{1}(\d*)/

还有一大堆其他类似的变体。我只是在寻找正确方向的指导。任何帮助将不胜感激!

最佳答案

此处使用非贪婪量词:

while ($_ =~ /(.*?)\|{1}\d*?\.{1}\d*?%{1}\|{1}(\d*)/) {
                 ^

我无法判断你的括号是字面的还是什么,但如果是字面的,你需要转义它们:

while ($_ =~ /(\(.*?\))\|{1}\d*?\.{1}\d*?%{1}\|{1}(\(\d*\))/) {
               ^^   ^^                              ^^  ^^

正如 @Tim 提到的,不需要 {1} 量词(恢复文字括号):

while ($_ =~ /(.*?)\|\d*?\.\d*?%\|(\d*)/) {

关于regex - 相当具体的 Perl 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17891672/

相关文章:

java - 如何在java中查找和替换某些字符串模式

regex - Bash Regex 如何检索值

perl - 怎么搭配\'

perl - 为什么 "import"子程序在 Perl 中没有大写

perl - 如何设置Raku的sqrt的精确度?

Javascript正则表达式仅匹配点作为标点符号,不匹配数字

regex - 带有多个单词的 git 匹配标签

javascript - 将字符串+Javascript中的多行替换为单行

perl - 如何重写这个评估 block

linux - 无法在 Debian 8x 上安装 libnet-server-perl