Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Regular Expressions - Using Not operator

I know this is probably quite straightforward but cannot seem to find an example of what I'm trying to do.

Matching from start of a string, i want to match building numbers.

i.e.

60 would match 60A and 60 but not 6000

likewise

1 would match 1 and 1ABC but not 11

/^1[^\0-9]*

is like what i need, matching 1 and any non numeric value any number of times. (granted this is from expresso - (.net) but it doesn't work in there.

can anybody point me in the right direction?

thanks,

Sam

like image 695
sambomartin Avatar asked Sep 20 '25 23:09

sambomartin


2 Answers

You can use regex /^1(?!\d)/ to match building 1.

THe (?!\d) is a negative lookahead and says "match 1, as long as it isn't followed by another number".

e.g.

myString.match(/^1(?!\d)/)
like image 107
mathematical.coffee Avatar answered Sep 22 '25 14:09

mathematical.coffee


If you want to put a variable in a regex, you can do something like:

var number = 60;
var re = new RegExp("^"+number+"(?!\\d)");

'60'.match(re);        // => ["60"]
'60A'.match(re);       // => ["60"]
'600   '.match(re);    // => null
'a60A'.match(re);      // => null
like image 33
Toto Avatar answered Sep 22 '25 14:09

Toto