Peterson Peterson - 6 months ago 28
AngularJS Question

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

  3. /* sdfsfeff *

  4. /* 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

Answer

Brackets means any of the contained char. So change your regex to:

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

You may read about Regex charclass


Side note:

  • you don't need to escape ., ?, (), * and {} within classes
  • a-zA-Z0-9_ is equivalent to \w.
  • within a char class, - means a range, thus \)-_ means from ) to _

I would write:

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

Or, if you want to capture anything (even multi-lines comments):

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

See demo