2

I'm trying to identify if the user has typed someone else's username if the typed an at symbol (@) before it, much like on twitter. My function can recognise the @ symbol and the username after it, but it includes the a spacebar after it (if there was one).

Here's my regex stuff

/@([A-Za-z0-9_]+)(\s|\Z)/

So let's say that a user typed

@testificate blah blah blah

My function would select the following (between the | symbols)

|@testificate |blah blah blah

When what I actually want is for it to select

|@testificate| blah blah blah

It includes the space afterwards and that's not what I want. Is there a better way to do this? I'm turning the @ tags into links with a preg_replace, can anyone help me out? Thanks

2
  • 1
    Can you show the preg_replace statement? Commented Nov 22, 2011 at 9:03
  • 1
    Be careful. This regular expression will erroneously match portions of e-mail addresses. You probably want to ensure that the character preceding the "@" is a nonword (\W) character. Commented Nov 22, 2011 at 9:17

1 Answer 1

2

why you add (\s|\Z) ?

\s space
\Z End of subject or newline at end

Regex: /@([A-Za-z0-9_]+)/

Edit:

davidchambers's suggestion

Shorter Regex: /@(\w)+/
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, I can't remember why.. must have been stuck in a train of thought that, looking back, doesn't make much sense now. Well that's awkward, but thanks for your answer! I'll mark it as the answer when I can :)
/@([A-Za-z0-9_]+)/ can be further simplified: /@(\w+)/. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.