Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用javascript编写特定的模式_Javascript_Html_Regex_Typescript - Fatal编程技术网

用javascript编写特定的模式

用javascript编写特定的模式,javascript,html,regex,typescript,Javascript,Html,Regex,Typescript,我有一个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)]="pro

我有一个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或以下运算符之一开头和后面的X:+,-,*,/,运算符后面应该有一个数字(浮点数也是),数字后面是运算符,运算符后面是另一个数字,依此类推

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

  • X
  • X*5466
  • X+2145/24525*3566
  • X-2345+31101/46704*2*2/8
  • X+4.2-43/88.33*123.11+5555

  • 如何用javascript编写此模式?

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

    /^X((\*|\+|\/|-)\d+)*$/
    
    或更短:

    /^X([\*\+\/-]\d+)*$/
    
    你可以测试一下

    console.log('Should match');
    log('X是'+isCorrect('X'));
    log('X*5466为'+isCorrect('X*5466'));
    console.log('X+2145/24525*3566为'+isCorrect('X+2145/24525*3566'));
    console.log('X-2345+31101/46704*2*2/8为'+isCorrect('X-2345+31101/46704*2*2/8');
    console.log('shouldnotmatch');
    log('Xi是'+isCorrect('Xi'));
    函数isCorrect(输入){
    返回输入。匹配(/^X([\*\+\/\-]\d+*$/)==null?false:true
    
    }
    到目前为止,您尝试了什么?你想用这个达到什么目的?我不是一个职业选手,这真的是一个反复尝试的过程,有很多坚持。但我肯定会添加一些更详细的信息,说明其中的功能。:)@乔杜穆斯,怎么样?这更清楚吗?我对正则表达式本身也做了一些小的改进。嗯,你是如何测试它的?我添加了一个可以运行的示例,它为我返回null。这是正确的,因为它不匹配。是的,这段代码工作起来很有魅力。谢谢你的回答@托斯卡夫
    ^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