【问题标题】:How to write Regex for input values? [closed]如何为输入值编写正则表达式? [关闭]
【发布时间】:2013-07-14 11:02:43
【问题描述】:

我可以使用什么正则表达式来解析字符串,使其只接受整数和/ 字符?

【问题讨论】:

标签: javascript regex


【解决方案1】:
var a = '123/4';
var b = 'e123/4';

变体 1

var regex = new RegExp('^[0-9/]+$');

console.log((a.match(regex)) ? true : false); // true
console.log((b.match(regex)) ? true : false); // false

变体 2

var regex = /^[0-9/]+$/;

console.log((a.match(regex)) ? true : false); // true
console.log((b.match(regex)) ? true : false); // false

变体 3

var regex = /^[\d\/]+$/;

console.log((a.match(regex)) ? true : false); // true
console.log((b.match(regex)) ? true : false); // false

【讨论】:

  • 为什么不var regex = /^[0-9/]+$/;
  • 我只是习惯了这样写。不过应该没什么区别吧?
  • 顺便说一句,您也可以将正则表达式写为/^[\d\/]+$/
  • 我认为使用构造函数的效率应该会稍低一些,因为你需要创建一个字符串对象并且有另一个函数调用的开销。另外,当您使用转义时,语法变得更加丑陋(因为您需要将所有反斜杠加倍)。我只会将构造函数用于动态创建(连接)模式。
猜你喜欢
  • 1970-01-01
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
相关资源
最近更新 更多