简体   繁体   中英

Javascript Regular Expression - Filter only integer string also negative

I'm trying to create a regex validation of a string and I want to check if string is an integer string, positive or negative.

I tryed to create my expression and I'm able to filter only digit with symbol '-' but I can't match as true string that begin with '-' (optional) and contains any digit at the end.

This is my try:

    var intRegex = /^[-?\d]+$/g;

    console.log(intRegex.test('55')); // true
    console.log(intRegex.test('artgz')); // false
    console.log(intRegex.test('55.3')); // false
    console.log(intRegex.test('-55')); // true
    console.log(intRegex.test('--55')); // true but I don't want this true
    console.log(intRegex.test('5-5')); // true but I don't want this true

Any idea?

you can use /^-?\\d+$/ , you want hyphen(-) only 0 or 1 times, so you use ? after -, and \\d can be 1 or more times so use + for \\d only.

 var intRegex = /^[-]?\\d+$/g; console.log(intRegex.test('55')); // true console.log(intRegex.test('artgz')); // false console.log(intRegex.test('55.3')); // false console.log(intRegex.test('-55')); // true console.log(intRegex.test('--55')); // true but I don't want this true console.log(intRegex.test('5-5')); // true but I don't want this true 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM