【问题标题】:Write a specific pattern in javascript用javascript写一个特定的模式
【发布时间】:2017-10-26 11:10:16
【问题描述】:

我有一个 html 输入,例如:

<div class="form-group">
 <div class="col-sm-6">
  <label for="inputCalculator"
         class="control-label">Calculation:</label>
  <input class="form-control"
         type="text"
         [(ngModel)]="properties.calculator"
         (keyup)="onKeyUpCalculator($event.key, 0)"
         placeholder="Enter Calculator:"
         id="inputCalculator"
         name="inputCalculator"
         autocomplete="off" />
  <div *ngIf="calculatorError"
        class="alert alert-danger">
        The pattern is incorrect
 </div>
</div>

如果输入文本来自这种模式,我想检查 js:

可以是字符串开头的 X OR X 开头和之后的下列运算符之一:+、-、*、/ 和之后运算符应该有一个数字(浮点数也是如此),数字后面是运算符,运算符后面是另一个数字,依此类推。

以下是有效输入的一些示例:

  1. X
  2. X*5466
  3. X+2145/24525*3566
  4. X-2345+31101/46704*2*2/8
  5. X+4.2-43/88.33*123.11+5555

如何在 javascript 中编写此模式?

【问题讨论】:

  • 到目前为止您尝试过什么?你想用这个来达到什么目的?
  • regex101.com 会很有帮助

标签: javascript html regex typescript


【解决方案1】:

匹配所有这些输入的正则表达式模式是。

/^X((\*|\+|\/|-)\d+)*$/

或更短:

/^X([\*\+\/-]\d+)*$/

你可以测试一下here

^X // start with X
   ( // start a new group for all the rest
      [\*\+\/-] // one of *,+,/,-
      \d+ // at least one digit
   )* // match stuff like *123 0 or multiple times
 $ // match the end of the line

console.log('Should match');
console.log('X is ' + isCorrect('X'));
console.log('X*5466 is' + isCorrect('X*5466'));
console.log('X+2145/24525*3566 is ' + isCorrect('X+2145/24525*3566'));
console.log('X-2345+31101/46704*2*2/8 is ' + isCorrect('X-2345+31101/46704*2*2/8'));

console.log('Should not match');
console.log('Xi is ' + isCorrect('Xi'));

function isCorrect(input) {
 return input.match(/^X([\*\+\/\-]\d+)*$/) == null ? false : true
}

对于浮点数,我们可以将正则表达式的 \d+ 部分替换为与浮点数匹配的部分,例如 [-+]?[0-9]*\.?[0-9]+

那么正则表达式将是:

/^X([\*\+\/-][-+]?[0-9]*\.?[0-9]+)*$/

【讨论】:

  • 我不是专业人士,这真的是反复试验,需要大量的坚持。但可以肯定的是,我会添加更多详细信息,说明其中的作用。 :)
  • @Jordumus 怎么样?这更清楚吗?我也对正则表达式本身做了一些小的改进。
  • hm 你是如何测试它的?
  • 我添加了一个可以运行的示例,它为我返回 null。这是正确的,因为它不匹配。
  • 是的,这段代码就像魅力一样。谢谢你的回答! @toskv
猜你喜欢
  • 2020-12-26
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
相关资源
最近更新 更多