Original address: Http://javascript.info/tutorial/regexp-introduction
Brief introduction
Regular expressions have a very powerful function for string "Find" and "replace". In JS, it is integrated in the string method: Search, match, and replace.
A regular expression, consisting of a pattern(matching rule) and a flags(modifier-optional).
A basic regular match is the same as a substring match. A string surrounded by a slash "/" can create a regular expression.
1 regexp =/att/ 2 3 str = "Show me the pattern!" 4 5 // -
In the example above, the Str.search method returns the regular "Att" in the string "Show me the pattern!" Position in the.
In practice, the regular formula may be more complex. The following regular matches the email address:
1 regexp =/[a-z0-9!$%& ' *+\/=?^_ ' {|} ~-]+(?:\. [a-z0-9!$%& ' *+\/=?^_ ' {|} ~-]+) *@ (?: [A-z0-9] (?: [a-z0-9-]*[a-z0-9])? \.) + (?: [A-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum) \b/23 str = Let'sfind a [email protected]here "45 alert (Str.match (regexp)) // [ Email protected]
The Str.match method outputs a matching result.
After completing this tutorial, you can not only fully understand the above regular style, but also create more complex regular style.
In the JS console, you can directly call the Str.match method to test the regular
1 alert ("lala". Match (/la/))
Here we will make the demo shorter and use the handy showmatch function to output the correct matching result:
1 showmatch ("Show Me The pattern!",/att/) // "att"
1 functionShowmatch (str, reg) {2 varres =[], matches;3 while(true) {4Matches =reg.exec (str)5 if(matches = = =NULL) Break6Res.push (matches[0])7 if(!reg.global) Break8 }9 alert (RES)Ten}
In the next tutorial, we will begin to learn the regular syntax.
Foreign language translation--javascript tutorial--regular expression--(1)