正则表达式匹配和打印字符串问题

时间:2017-04-01 11:30:23

标签: regex perl

在Perl中,我试图匹配三个组。有些团体围绕着他们有两个问号,其他人有一个问号。我需要能够区分这两者。

示例输入:

The box is ?Red? in colour.
The box is ??green?? in colour. 

当前输出:

The box isRedin colour.

The box is green in colour. 

期望输出:

The box is Red in colour.

The box is green in colour. 

这几乎是完美的工作:

my $pattern_q  = '(.*\s?)[^\?]\?(\w.*)\?[^\?](.*)';
my $pattern_qq = '(.*\s?)\?\?(\w.*)\?\?(.*)';

if ( $line =~ /$pattern_q/ ) {
    print "\n" . $1 . $2 . $3 . "\n";       
}

if ( $line =~ /$pattern_qq/ ) {
    print "\n" . $1 . $2 . $3 . "\n";

当我与$pattern_qq匹配时 - 它会正确处理所有内容,但最后\n除外,我可以使用。

当我与$pattern_q匹配时 - 它会删除我想要保留的三个组之间的空格。

3 个答案:

答案 0 :(得分:1)

你说:我需要能够区分这两个。但是因为你想要的输出在两种情况下是相同的并且没有显示出任何差异,在下面的例子中它通过以下方式证明:

  • public interface ICaller{ int DoStuff(dynamic parameters); } internal class ServiceForA : ICaller { internal int DoStuff(dynamic parameters) { //implementation } } internal class ServiceForB : ICaller { internal int DoStuff(dynamic parameters) { //implementation } } public class ServiceProcessor { private ICaller _service; public ServiceProcessor(ICaller service) { _service = service; } public int Invoke(ICaller service) { return _service.DoStuff(dynamic parameters); } } static void Main() { var processor = new ServiceProcessor(new ServiceForA()); processor.Invoke(); var processor = new ServiceProcessor(new ServiceForB()); processor.Invoke(); } 将为大写,
  • ??str??小写。
?str?

输出:

use 5.014;
use warnings;

while(<DATA>) {
    chomp;
    say "orig: [$_]";
    s/ (\?(\?)?) (\w+?) (\1) / $2 ? uc($3) : lc($3) /gex;
    say "new : [$_]";
}

__DATA__
The box is ?Red? in colour.
The box is ??green?? in colour. 
The box is ?Red? but inside is an ??green?? one
Aren't nicer the ?blue?? Or the ??violet???
What?  ??blue?  ???violet??!

你也可以用子程序调用替换orig: [The box is ?Red? in colour.] new : [The box is red in colour.] orig: [The box is ??green?? in colour. ] new : [The box is GREEN in colour. ] orig: [The box is ?Red? but inside is an ??green?? one] new : [The box is red but inside is an GREEN one] orig: [Aren't nicer the ?blue?? Or the ??violet???] new : [Aren't nicer the blue? Or the VIOLET?] orig: [What? ??blue? ???violet??!] new : [What? ?blue ?VIOLET!] ,例如:

$2 ? uc($3) : lc($3)

具有相同的输出。

答案 1 :(得分:0)

正如你所说,你的代码已经完全正常工作了#34;它非常接近于完全按照自己的意愿行事。

您可以通过在第一个模式中移动两个括号来使其完全符合您的要求,以在捕获组中包含[^\?]模式匹配。这将捕获样本输入中?Red?两侧的空格。

所以

'(.*\s?)[^\?]\?(\w.*)\?[^\?](.*)'

变为

'(.*\s?[^\?])\?(\w.*)\?([^\?].*)'

答案 2 :(得分:-2)

纯正则表达式替换示例here

Perl脚本代码(可以测试它here):

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @strings = (
    'The box is ?Red? in colour.',
    'The box is ??green?? in colour.'
);

local $" = "\n\t";

print "Before:\n\t @strings\n";

s/\?+(\w+)\?+/$1/ for @strings;

print "After:\n\t @strings\n";