Jump to content


Photo

Check first character matches the last character in a string


  • Please log in to reply
4 replies to this topic

#1 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 15 September 2006 - 08:38 AM

Morning all,

I have the following expression which I think works well.  What I want in short is a string to start and end with the same character, with atleast one thing in between.

/^(.).+\1$/

Below is the details of what I think the above does, but wondered if there's a better way to do it...

1. Start at the beginning of the line
2. Capture the first character, doesn't matter what it is
3. Then there has to be another character, again, doesn't matter what, but has to be atleast one
4. Then an identical character to the first
5. Then the end of the line

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#2 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 15 September 2006 - 01:56 PM

1 is the literal number "1". You want the first backreference, which is \1.
Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/

#3 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 15 September 2006 - 03:29 PM

Effigy, that's what I had, I copied and pasted it direct from the script.

It's an issue with putting the [ php ] [ /php ] tags around it, they stripped it out.

Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#4 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 15 September 2006 - 03:42 PM

Ahh. Then the expression you have looks good. Just keep in mind that . matches everything but a new line without the /s modifier, and that your pattern will only match one line without the /m modifier.
Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/

#5 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 15 September 2006 - 03:49 PM

That's perfect, I'm only matching on a single line and I certianly don't want to use the /s modifier.

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users