String matching: Difference between revisions
Content added Content deleted
(Updated D entry) |
(→{{header|Perl}}: present the answer in a more reader-friendly way) |
||
Line 1,551: | Line 1,551: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
<lang perl># the first four examples use regular expressions, so make sure to escape any special regex characters in the substring |
|||
Using regexes: |
|||
"abcd" =~ /^ab/ #returns true |
|||
"abcd" =~ /zn$/ #returns false |
|||
<lang perl>$str1 =~ /\Q$str2\E/ # true if $str1 contains $str2 |
|||
"abab" =~ /bb/ #returns false |
|||
$str1 =~ /^\Q$str2\E/ # true if $str1 starts with $str2 |
|||
$str1 =~ /\Q$str2\E$/ # true if $str1 ends with $str2</lang> |
|||
my $loc = index("abab", "bb") #returns -1 |
|||
$loc = index("abab", "ab") #returns 0 |
|||
Using <code>index</code>: |
|||
$loc = index("abab", "ab", $loc+1) #returns 2</lang> |
|||
<lang perl>index($str1, $str2) != -1 # true if $str1 contains $str2 |
|||
index($str1, $str2) == 0 # true if $str1 starts with $str2 |
|||
rindex($str1, $str2) == length($str1) - length($str2) # true if $str1 ends with $str2</lang> |
|||
Using <code>substr</code>: |
|||
<lang perl>substr($str1, 0, length($str2)) eq $str2 # true if $str1 starts with $str2 |
|||
substr($str1, - length($str2)) eq $str2 # true if $str1 ends with $str2</lang> |
|||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |