regex - Perl 正则表达式

标签 regex perl parsing scripting

我继承了一个从某些文件中提取数据的 perl 脚本。整个脚本运行良好,但最近一些工程师在某个位置输入了多个数字,而这些数字通常只有一个数字,因此输出并未显示所有预期内容。

样本输入:
CRXXXX: "Then some text"CRs XXXX, XXXX, XX, XXXCRXXX "Some Text"
目前,这个正则表达式语句在 CR 之后提取了数字,但是如果给出示例输入的第二行,它会打印 "s XXXX, XXXX, XX, XXX"而不是想要的 "XXXX XXXX XX XXX"
我对 perl 很陌生,正在努力弄清楚如何改变这个正则表达式以处理所有输入。

 $temp_comment =~ s/\s[cC][rR][-\s:;]*([\d])/\n$1/mg;

提前致谢!

布洛克

最佳答案

对于示例数据,例如:

my $temp_comment =
'CR1234: "Then some text"
 CRs 2345, 3456, 45, 567
 CR678 "Some Text"';

尝试:
$temp_comment =~ s/(,)|[^\d\n]+/$1?' ':''/semg;

或者,如果您想接近字符串模板:
$temp_comment =~ s/ ^                 # multi-line mode, line start
                    \s*               # leading blanks?
                    CR                # CR tag
                    \D*               # non-number stuff
                     (                  # start capture group
                      (?:\d+ [,\s]*)+   # find (number, comma, space) groups
                     )                  # end capture group
                    \D*               # skip remaining non-number stuff
                    $                 # multi-line mode, line end
                  /$1/mxg;            # set multi-line mode + regex comments "x" 

但是您必须在后续步骤中删除数字组中的逗号。
$temp_comment =~ tr/,//d;             # remove commas in the whole string

或者
$temp_comment =~ s/(?<=\d),(?=\s\d)//g;  # remove commas between numbers '11, 22'

对于“单步”,您必须使用 /e 修饰符:
$temp_comment =~ s{ ^                 # line start
                    \s*               # leading blanks?
                    CR                # CR tag
                    \D*               # non-number stuff
                    ((?:\d+ [,\s]*)+) # single or group of numbers
                    \D*               # non number stuff
                    $                 # line end
                  }
                  {do{(local$_=$1)=~y/,//d;$_}}mxeg;

根据上述数据,这将导致:
1234
2345 3456 45 567
678 

但实际上, 请使用 ,如果可能的话, 更简单的两步方法 。后一个正则表达式可能是您的继任者的维护噩梦。

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

相关文章:

linux - Perl脚本在linux终端中运行,但在浏览器中出现错误

java - 将单行 HTML 文件分割为格式良好的 HTML 文件

php - 正则表达式从任何字符串中获取日期 yyyy-mm-dd

php - 如何通过文本搜索实现基于 Web 的查找文件数据库

python - 使用正则表达式在 'hello' 中查找 'man' 、 '' 和 '/?user=hello&user=man&user='

perl - 为什么@@、@!、@等不在字符串中插入?

java - 在 java 中为 Android 应用程序解析 html

c++ - boost::spirit::qi 编译器错误:没有转换运算符无法将 'const some_stuff::return_type' 转换为 'unsigned int'

ios - 在 iOS Swift 上使用 RegEx 验证密码

javascript - 如何使用正则表达式匹配字符串中的单词并对每个匹配执行特定任务