regex - Match string with escape characters or backslashes -


the following perl script , testdata simulate situation can find 2 instead of 4 expected. (to match support.tier.1 backslash in between).

how can modify perl regex here? thanks

my @testdata(     "support.tier.1",     "support.tier.2",     qw("support\.tier\.1"),     "support\.tier\.2",     quotemeta("support.tier.1\@example.com"),     "support.tier.2\@example.com",     "support\.tier\.1\@example\.com",     "support\.tier\.2\@example\.com",     "sales\@example\.com" ); 

here code changed:

my $count = 0; foreach $tier(@testdata){     if($tier =~ m/support.tier.1/){         print "$count: $tier\n";     }     $count++; } 

i 2 matches while expected 4:

0: support.tier.1 6: support.tier.1@example.com 

update

since seems may indeed getting strings containing backslashes, suggest use string::unescape remove backslashes before testing strings. have install isn't core module

your code this

use strict; use warnings;  use string::unescape;  @tiers = (   "support.tier.1",   "support.tier.2",   qw("support\.tier\.1"),   "support\.tier\.2",   quotemeta("support.tier.1\@example.com"),   "support.tier.2\@example.com",   "support\.tier\.1\@example\.com",   "support\.tier\.2\@example\.com",   "sales\@example\.com", );  $count = 0;  $tier ( @tiers ) {    $plain = string::unescape->unescape($tier);    if ( $plain =~ /support\.tier\.1/ ) {     printf "%d: %s\n", ++$count, $tier;   } } 

output

1: support.tier.1 2: "support\.tier\.1" 3: support\.tier\.1\@example\.com 4: support.tier.1@example.com 

note there bug in string::unescape module prevents exporting unescape function. means have use string::unescape::unescape or string::unescape->unescape time. or import manually *unescape = \&string::unescape::unescape



the @tiers array contains these exact strings

  1. support.tier.1
  2. support.tier.2
  3. "support\.tier\.1"
  4. support.tier.2
  5. support\.tier\.1\@example\.com
  6. support.tier.2@example.com
  7. support.tier.1@example.com
  8. support.tier.2@example.com
  9. sales@example.com

can see items 1 , 7 contain string support.tier.1? other 2 imagine expected match 3 , 5, contain spurious backslashes

it's not clear, seems unlikely getting data in format. if want match support.tier.1 either dot may preceded backslash character need /support\\?\.tier\\?\.1/, think misunderstanding way perl strings work


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -