Perl Testing a string for a substring
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Testing a string for a substring

  1. #1
    John E is offline Elite Member Power Poster
    Join Date
    Apr 2001
    Location
    Manchester, England
    Posts
    4,218

    Testing a string for a substring

    I understand that if I have a string in perl called "my_str" and it happens to be "Tuesday" I can test it like this:-

    Code:
    if ($my_str eq Tuesday) {
    #  do something here, because it's Tuesday !
    }
    But suppose I want to test for the substring "day" - so that "daytime", "Monday", "Tuesday", "Saturday" etc would all would all provide a positive match - how can I achieve that with perl


    [Footnote...] I discovered a way to achieve this using the index statement - e.g.

    Code:
    if (-1 != index($my_str, "day")) {
    #  do something
    }
    but I assume that'll probably be case sensitive. Case sensitivity isn't necessarily undesirable but I just wondered if there's any other function available that's more elegant / more suited to string searches?
    Last edited by John E; September 28th, 2013 at 11:48 AM.
    "A problem well stated is a problem half solved. - Charles F. Kettering

  2. #2
    PeejAvery's Avatar
    PeejAvery is offline Super Moderator Power Poster
    Join Date
    May 2002
    Posts
    10,839

    Re: Testing a string for a substring

    Rather than use index, you can just use a case insensitive regular expression match.

    Code:
    if ($string =~/findme/i) {
      ...
    }
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center