Foreign language translation--javascript tutorial--regular expression--(1)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.