locked
Match First and Last character RRS feed

  • Question

  • Hi,

    I want to create a regular expression validation. I want to ensure that the string enter has the same first and last character.

    Eg: Idli - valid

    axa -valid

    aluminia - valid

    igloo - invalid

    excuse - valid

    1elbow1 - valid

    -apple- - valid

    pickaboo - invalid.

    Can someone please provide me with the right regex.

    Thank you in advance

    Regards,

    gmatnj


    • Edited by gmatnj Thursday, November 8, 2012 6:53 PM
    Thursday, November 8, 2012 6:52 PM

Answers

All replies

  • ^(.).*?(\1)$

    Match will be valid if the first character matched ^(.) is the same as what the last character (\1)$ at the end is. \1 is a backreference to the first match.

    See Regular Expression Quick Reference for more.


    William Wegerson (www.OmegaCoder.Com)

    • Marked as answer by gmatnj Thursday, November 8, 2012 7:54 PM
    Thursday, November 8, 2012 7:13 PM
    Moderator
  • Thank you very much. That is outstanding.

    In this case :

    ThaT - is valid

    That - is not valid.

    How can i allow for this case as well?

    Thank you,

    gmatnj

    Thursday, November 8, 2012 7:38 PM
  • It is a regex option IgnoreCase see RegexOptions.


    William Wegerson (www.OmegaCoder.Com)

    • Marked as answer by gmatnj Thursday, November 8, 2012 7:54 PM
    Thursday, November 8, 2012 7:49 PM
    Moderator
  • Outstanding. Thank you.
    Thursday, November 8, 2012 7:54 PM