I want to know how to write the regular expression in javascript. Please help me. Give a simple example with details. I mean the source code (i am using asp.net开发者_运维问答 and c# language).
There are tons of examples online for using JavaScript's RegExp object. Start with this.
Here is a simple example of creating a RegExp and then using it to determine whether there is at least one occurrence of the word "dog" in the passed string.
var myString = "I wish all dogs were brown.";
var myRegExp = new RegExp("dog");
var containsDog = myRegExp.test(myString);
In this example, containsDog would be 'true'.
You may want to refer concise article on : www.regular-expressions.info/javascript.html
First you need to understand the concept of regular expression. Once you know what regex is, writing them in any language is not difficult.
You can read these
Regular Expressions
Regular Expressions patterns
String and Regular Expression methods
If you are interested in buying a regex book then this one is good
Regular Expressions Cookbook
I think the following articles from Mozilla Dev Center are a very good introduction:
- Regular Expressions.
- Working with Regular Expressions.
- Examples of Regular Expressions.
You can write a regular expression literal enclosed in slashes like this:
var re = /\w+/;
That matches something that contains one or more word characters.
You can also create a regular expression from a string:
var re = new RegExp("\\w+");
Notice that since that's a string literal, I have to double the backslash to escape its special meaning for strings.
This should also work:
var myString = "I wish all dogs were brown.";
if (myString.match(/dog/i))
{
//do something
}
精彩评论