0

I need to find a string like this @[0000:0000:Username] in a text.

Then I need to extract the first number sequence (user-id) and the Username. Then I need to replace them with a link.

I'm able to extract the first number sequence but the Username is variable. It can have multiple words (and spaces) but it can also be a single word e.g "John", "John Doe", "John Doe Junior".

The Username can contain alphanumeric characters, periods, underscores and dashes.

This is what I have now with username up to 4 words:

/@\[(\d*):\d*:(\S*|\S*\s*\S*\s*\S*\s*\S*)\]/

And this is the link I'd like to create:

<a href="http://www.facebook.com/user-id/" target="_blank">Username</a>

I'm trying to it like this:

<a href="http://www.facebook.com/$1/" target="_blank">$2</a>

This works fine if only one match is found. As soon as there's more matches it messes up.

Any help would be greatly appreciated.

3
  • @AmalMurali It won't allow more than 4 words in the username. Commented Dec 31, 2013 at 11:58
  • @Barmar: Well, the OP says Obviously this doesn't work.. It does (for the examples shown in the question anyway). I think the question could be improved by explaining all your requirements, @Ziggy. Commented Dec 31, 2013 at 12:02
  • He said "with username up to 4 words". That's his way of describing the unwanted limitation. Commented Dec 31, 2013 at 12:10

3 Answers 3

1

This should do the trick:

/@\[(\d+):\d+:([^\]]+)\]/

[^]] searches for all characters that are not ], so basically everything up to the final ]

Sign up to request clarification or add additional context in comments.

1 Comment

The second capture should be the username, not the second number.
0

Try:

/@\[(\d*):\d*:([\w. \-]*)\]/m

[\w. \-] matches a letter, number, underscore, period, space, and dash. * after it allows any number of these.

8 Comments

yes, you do need to escape -. It's the range operator, as in A-Z.
His original regexp says \d*. Since that wasn't the part he's having a problem with, I assumed it's what he wants.
See stackoverflow.com/questions/20758841/… for what happens if you forget to escape -.
That's true. But since I didn't put it there, I needed to escape it. This is a simpler, safer, more general way to do it.
no need to escape - at the beginning or at the end of character class.
|
0
@\[(\d+):\d+:([-\w. ]+)\]

Live demo

1 Comment

And this one too. Thanks folks!

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.