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
support.tier.1support.tier.2"support\.tier\.1"support.tier.2support\.tier\.1\@example\.comsupport.tier.2@example.comsupport.tier.1@example.comsupport.tier.2@example.comsales@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
Post a Comment