view raw
Peterson Peterson - 11 months ago 114
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:


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!



<script src="" ></script>
<script src=""></script>

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

<form name="form1" novalidate>
<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>

//module declaration
var app = angular.module("myApp",['ngMessages']);
//controller declaration
//code goes here ...




Regular expression include and exclude special characters


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


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:


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


See demo