karatecode
karatecode

Reputation: 584

How to detect something does not exist before 'end of string' in regex

I have a simple regular expression looking for twitter style tags in a string like so:

$reg_exUrl = "/@([A-Za-z0-9_]{1,15})/";

This works great for matching words after an @ sign.

One thing it does though which I don't want it to do is match full stops.

So it should match

"@foo"

but should not match

"@foo."

I tried adding amending the expression to dissallow full stops like so:

$reg_exUrl = "/@([A-Za-z0-9_]{1,15})[^\.]/";

This almost works, except it will not match if it's at the end of the string. EG:

It WILL match this "@foo more text here"

but won't match this "@foo"

Could anyone tell me where I'm going wrong?

Thanks

Upvotes: 2

Views: 227

Answers (3)

Smern
Smern

Reputation: 19066

It's not working if it's at the end of the string because it's expecting [^\.] after it.

What you are wanting, you can do with a negative lookahead to make sure there is no dot afterwards, like this:

/@([A-Za-z0-9_]{1,15})(?![^\.]*\.)/

enter image description here

Test it here


You could also do it this way:

/@([A-Za-z0-9_]{1,15})([^\.]*)$/

enter image description here

Test it here

This one allows for optional characters other than a dot, and then it has to be the end of the string.

Upvotes: 2

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

First of all your original expression can be written like the following:

/@\w{1,15}/

because \w is equivalent to [A-Za-z0-9_].

Secondly your expression doesn't match names with . so you probably meant that you don't want to match names ending with a dot and this can be done with the following:

/@\w{1,15}(?![^\.]*\.)/

Or if you want to match a name no matter how long it is just not ending with a dot then

/@\w+(?![^\.]\.)/

Oh ya, I forgot one thing, your problem was caused by the absence of any anchor characters such as the start of line ^ and end of line $, so you should use them if you want to match a string that contains only a twitter name which you wish to validate.

Summary: If you want to match names anywhere in the document don't use anchors, and if you want to know whether a given string is a valid name use the anchors.

Upvotes: 3

Paul
Paul

Reputation: 141827

A $ matches the end of the string, and for future reference, a ^ matches the begining:

$reg_exUrl = "/@([A-Za-z0-9_]{1,15})$/";

Upvotes: 1

Related Questions