Regular Expression that matches only 1-digit numbers, and nothing else

3

I have a variable that can store several values (words, letters, numbers, etc.), depending on an insert in an input type field. I would like to do a search that lists only 1-digit numbers (/ \ b \ d {1} \ b /), and any other information present in the "false" field as a result. Ex:

var test = "1";
console.log(test.match(/\b\d{1}\b/)); // corresponde e portanto é 'true'
var test = "sp 1 inf"; // mesmo assim corresponde com "test.match(/\b\d{1}\b/)"

What I want is a modification in "test.match (/ \ b \ d {1} \ b /)" which gives "false" as a result in the second case (var test="1 info"), , not matching. Thanks in advance for your attention.

    
asked by anonymous 12.03.2015 / 02:27

2 answers

6

When using match , look for some string (substring) in the string that matches the regular expression used, wherever it is. Because your string contains a single, isolated digit, it finds that digit and returns true.

If you want the expression to match the entire string , not only part of it, use ^ at the beginning to match the "beginning of the string" and $ at the end to match the " end of string ":

^\b\d{1}\b$

Example (also substituting% with% with% with%, since this is sufficient to match a single character):

var test = "1";
log(test.match(/\b\d\b/)); // corresponde e portanto é 'true'
log(test.match(/^\b\d\b$/)); // corresponde e portanto é 'true'

var test = "sp 1 inf";
log(test.match(/\b\d\b/)); // corresponde e portanto é 'true'
log(test.match(/^\b\d\b$/)); // não corresponde e portanto é 'false'


function log(x) {
  document.getElementsByTagName("body")[0].innerHTML += "<p>" + x + "</p>";
}
    
12.03.2015 / 02:43
1

If you create a catch group for a number with (\d) and give the global g flag to catch all cases you will have an array with length corresponding to the number of digits present in the string (or null if there are no numbers in the string).

So if you want to know if there is one and only one number you can check if that array that the match returns has only one element, array.length == 1 .

function testa(str) {
    var match = str.match(/(\d)/g);
    return !!match && match.length == 1;
}

var a = "1"; 
var b = "sp 1 inf";
var c = "sp 1 inf 5";
var d = "sp inf";

console.log(testa(a)); // true
console.log(testa(b)); // true
console.log(testa(c)); // false (length é 2)
console.log(testa(d)); // false (match é null)

jsFiddle: link

    
12.03.2015 / 07:54