简体   繁体   English

包含数字的字符串的Javascript正则表达式

[英]Javascript regex for string with a number in it

I'm currently working within an AngularJS directive and in the template I'm attempting to check if a an instance variable of the Controller is a certain type of string. 我目前在AngularJS指令中工作,并且在模板中尝试检查Controller的实例变量是否为某种字符串。

Specifically, this string can be anything at all so long as it has an 8-digit number in it. 具体来说,该字符串可以是任何东西,只要其中包含8位数字即可。
Passing Examples: "gdbfgihfb 88827367 dfgfdg", "12345678", ".12345678" The number has to be a solid string of 8 numbers with nothing in between. 通过的示例:“ gdbfgihfb 88827367 dfgfdg”,“ 12345678”,“。12345678”该数字必须是由8个数字组成的实字符串,且中间没有任何数字。

I've tried this: 我已经试过了:

$ctrl.var == /[0-9]{8}/ 

But it doesn't work for some reason. 但是由于某种原因,它不起作用。 How do I construct a regex in order to do this? 我该如何构造一个正则表达式呢?

Thanks 谢谢

Your regex is fine but the comparison is wrong. 您的正则表达式很好,但是比较是错误的。 You want 你要

/\d{8}/.test($ctrl.var)

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test 参见https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

 let tests = ["gdbfgihfb 88827367 dfgfdg", "12345678", ".12345678", "nope, no numbers here"], rx = /\\d{8}/; tests.map(str => document.write(`<pre>"${str}": ${rx.test(str)}</pre>`)) 

Code: 码:

var first = "gdbfgihfb 88827367 dfgfdg";
var second = "12345678";
var third = ".12345678";

var reg = new RegExp('[0-9]{8}');

console.log(first.match(reg));
console.log(second.match(reg));
console.log(third.match(reg));

Output: 输出:

[ '88827367', index: 10, input: 'gdbfgihfb 88827367 dfgfdg' ]
[ '12345678', index: 0, input: '12345678' ]
[ '12345678', index: 1, input: '.12345678' ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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