in reply to Regular Expression: search two times for the same number of any signs

Hello,

you can play with length and more less greediness like in the following example (for sure while i'm writing you had received better answers)

use strict; use warnings; while (<DATA>){ chomp; $_=~/x(.*?)x(.*)x$/; if (length $1 == length $2){ print "OK $_\t [$1]",length $1," [$2]",length $2,"\n"; } else{print "$_ NOT OK\t[$1]",length $1," [$2]",length $2,"\n";} } __DATA__ xxx x.x.x x12x..x x123x...x x123x.x.x x12x1x # out OK xxx []0 []0 OK x.x.x [.]1 [.]1 OK x12x..x [12]2 [..]2 OK x123x...x [123]3 [...]3 OK x123x.x.x [123]3 [.x.]3 x12x1x NOT OK [12]2 [1]1

L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
  • Comment on Re: Regular Expression: search two times for the same number of any signs
  • Download Code

Replies are listed 'Best First'.
Re^2: Regular Expression: search two times for the same number of any signs
by Anonymous Monk on Nov 29, 2016 at 10:37 UTC
    Very nice approach ! But it does not work when in the first any sign part is a "x"
    "x1x2x...x" # should be valid is x.{3}3x.{3}x, but is NOK OK
      Ok you are right,

      so because i have no patience at all with regexes you can exploit the fact that your valid strings are always odd; they start and end with x and another x must be in the middle.

      use strict; use warnings; while (<DATA>){ chomp; # note the string IS always odd my $inter = int ((length $_) / 2)-1; my @char = $_=~/./g; if (scalar @char % 2 < 1){ print "Not OK $_ (unbalanced)\n"; next; } if ( $char[0] eq $char[$inter+1] and $char[0] eq $char[-1] and $char[0] eq 'x' ){ print "$_\t\tOK\n"; } else { print "NOT OK $_\t[$char[0] $char[$inter+1] $char[-1]]\n"; } } __DATA__ xxxxx x1x2x...x xxx x.x.x x12x..x x123x...x x123x.x.x x12x1x # out xxxxx OK x1x2x...x OK xxx OK x.x.x OK x12x..x OK x123x...x OK x123x.x.x OK Not OK x12x1x (unbalanced)

      L*

      UPDATE: it can be semplified, or golfed, a lot using 5.010

      use strict; use warnings; use 5.010; while (<DATA>){ chomp; # note the string IS always odd if ((length $_) % 2 < 1){ print "Not OK $_ (unbalanced)\n"; next; } if (($_=~/./g)[0,(int((length $_)/2)-1),-1]~~[qw(x x x)]){ print "$_\t\tOK\n"; } else { print "NOT OK $_\n"; } }

      L*

      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.