Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
Welcome to the Monastery
 
PerlMonks  

How can I find the first position of a substring case-insensitively?

( #44327=categorized question: print w/ replies, xml ) Need Help??
Contributed by ChilliHead on Dec 01, 2000 at 15:25 UTC
Q&A  > strings


Description:

I'm using index($mystr,"a") but I want to be able to check for "A" as well as "a".

Is it possible to make index case insensitive?

Answer: How can I find the first position of a substring case-insensitively?
contributed by eg

The easiest thing to do would be to use lc on $mystr like so:

  my $index = index( lc( $mystr ), "a" );
Edited by Russ: Combined posts by ambiguous, tektsu, kilinrax, ariels, and tenatious into one
Answer: How can I find the first position of a substring case-insensitively?
contributed by ambrus

You could use regexps, like this:

$needle = "a"; $haystack =~ /\Q$needle\E/i; $index = $-[0];
this works even if $needle has regexp-metacharacters in it.

But @- exists only in newer perls (from 5.6.1 I think). In perl 5.005 you could use something like

$needle = "a"; $haystack =~ /\Q$needle\E/i; $index = pos($haystack)-length($needle);
or
$needle = "a"; $haystack =~ /\Q$needle\E/i; $index = length($`);
but note that $` makes perl slower.

Whitespace added by tye

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others studying the Monastery: (11)
    As of 2014-04-18 13:58 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      April first is:







      Results (469 votes), past polls