简体   繁体   English

具有预定义的开始和结束模式的正则表达式

[英]Regex with predefined start and end pattern

My regex pattern must start with /* and must end with */; 我的正则表达式模式必须以/ *开头,并且必须以* /结尾; between this it might contain all alphabets, numbers, special characters - zero or more times. 它之间可能包含所有字母,数字,特殊字符 - 零次或多次。

I have made the following regex expression for this: 我为此做了以下正则表达式:

 [/*][a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*[*/;]

But this expression does not show error for patterns such as: 但是这个表达式不会显示模式的错误,例如:

  1. /* / *
  2. / * sdfsdff / * sdfsdff
  3. /* sdfsfeff * / * sdfsfeff *
  4. /* fefef3323 */ / * fefef3323 * /

Which is wrong. 哪个错了。 It must start with /* and end with */; 它必须以/ *开头并以* /结尾; at any cost. 不惜一切代价。

Following is angular code for testing this pattern. 以下是用于测试此模式的角度代码。 Pls someone help out! 请别人帮忙!

CODE: 码:

<html>

<head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js" ></script> 
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-messages.min.js"></script> 
</head>

<body ng-app="myApp" ng-controller="myCtrl">

<form name="form1" novalidate>
    {{form1.age.$error}}
    <input type="text" name="age" ng-model="myAge" ng-pattern="/^[/*][a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*[*/;]$/" />
    <div ng-messages="form1.age.$error" >
        <span ng-message="pattern">This field has wrong pattern.</span>
    </div>
</form> 

<script>
//module declaration
var app = angular.module("myApp",['ngMessages']);
//controller declaration
app.controller('myCtrl',function($scope){
    //code goes here ... 
});
</script> 

</body>

</html>

Reference: 参考:

Regular expression include and exclude special characters 正则表达式包括和排除特殊字符

http://www.regular-expressions.info/repeat.html http://www.regular-expressions.info/repeat.html

Brackets means any of the contained char. 括号表示任何包含的 char。 So change your regex to: 所以将你的正则表达式改为:

\/\*[a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*\*\/;

You may read about Regex charclass 您可以阅读有关Regex charclass的信息


Side note: 边注:

  • you don't need to escape . 你不需要逃避. , ? ? , () , * and {} within classes 类中的, ()*{}
  • a-zA-Z0-9_ is equivalent to \\w. a-zA-Z0-9_相当于\\ w。
  • within a char class, - means a range, thus \\)-_ means from ) to _ 在char类中, -表示范围,因此\\)-_表示从)到_

I would write: 我会写:

\/\*[-\w~@#^$&*()+=\[\]{}|\\,.?\s]*\*\/;

Or, if you want to capture anything (even multi-lines comments): 或者,如果您想捕获任何内容 (甚至是多行注释):

\/\*[\w\W]*?\*\/;

See demo 演示

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

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