View Full Version : regExp

Mr J
08-05-2006, 10:23 AM

Is there a regExp that will find the position of the last alphabetical character in a string.

In this example the last character would be d



08-05-2006, 11:34 AM
Try this.

var idx = str.search(/[a-z][^a-z]*$/i);

Mr J
08-05-2006, 02:14 PM
Thanks Kravvitiz, that sure beats looping through the string :thumbsup:

Mr J
08-05-2006, 02:42 PM
Sorry to post again but what would the expression be to find the last non numerical character in the string :o

I have tried

var idx = str.search(/[^0-9]*$/)

08-05-2006, 02:48 PM
off the top of my head, i believe that'd be
var idx = str.search(/\D\d*$/i);

Mr J
08-05-2006, 03:09 PM
Hi Joh6nn and thanks.

var idx = str.search(/\D*$/i);

returns the index of the end of the string, I also tried

var idx = str.search(/[^0-9]/);

but that returned zero

basically what I am after is getting the number at the end of a string


My last try was

var idx = str.search(/[0-9]*$/)

which does appear to work but I do not know enough about regExp to know if it is valid

08-05-2006, 03:17 PM
i made a typo in my first post, and edited it, but looks like only after you'd already seen it.

the solution you came up with looks like it should work, but you should test in thorougly, just in case. if you're new to REs, Liorean has a pretty good tutorial at evolt.org (http://evolt.org/node/36435).

08-05-2006, 09:36 PM
This finds the index of the first numerical character of any numerical characters at the end of the string.

var idx = str.search(/[0-9]*$/)

What you want is what joh6nn posted, which could also be written like this:

var idx = str.search(/[^0-9][0-9]*$/i);

Philip M
08-05-2006, 10:22 PM
This finds the index of the first numerical character of any numerical characters at the end of the string.

var idx = str.search(/[0-9]*$/)

I have tried this and get the folllowing:-

abc123 returns 3

abc123xyz returns 9

123abc returns 6

123abc789 returns 6

a returns 1

0 returns 0

So the regex returns the index of the last alpha character in the string.

Something wrong here??? WIN98SE and IE5.5

08-05-2006, 10:37 PM
Compare those to what you get with the RegExp that joh6nn posted there's a difference of 1.

Mr J
08-05-2006, 11:45 PM
It looks like both could be used to get the result I want.

The method Joh6nn posted

var idx = str.search(/\D\d*$/i);

works and gets the index of the last alpha character whereby any remaining numbers in the string can be found, hence



On the other hand

var idx = str.search(/[0-9]*$/)

finds the beginning of the numbers at the end of the string

result = str.substring(idx,str.length)

both display 123

08-05-2006, 11:51 PM
If that's what you want to do with it, then it doesn't matter.

My point is that those two RegExp produce different results.

Mr J
08-06-2006, 09:07 AM
I am happy to use either and I would like to thank you all for your time and help :thumbsup: