Getting Started with regular expressions

Source: Internet
Author: User

Speaking of regular expression, I believe many masters and Daniel are not unfamiliar, but I this year do not write a regular person is still do not know how to start, recently just contact some, summarize the basic points, the first to deepen the memory, the second share to me as a beginner as a learning reference:

Yes, please be like this: a period of time in the development process encountered a requirement, from the database to query the image address, in the program need to add a domain name, and then all the "\" Replace all the "/", and finally replace the different size format. Already have a similar code implementation, just copy to modify it, but found that the use of C # string. Replace () method realism is somewhat stretched (the code does not seem to be concise) so I want to implement this function with regular expressions.

1        /// <summary>2         ///use array splitting to get the URL of a picture of the specified size3         /// </summary>4         /// <param name= "ImagePath" >picture path E.g:string ImagePath = @ "\img\home\logo.png";</param>5         /// <param name= "Size" >picture size in Resource folder</param>6         /// <param name= "DefaultPath" >Default return path</param>7         /// <returns>formatted picture path E.g:/img/home/logo_180.png</returns>8          Public Static stringGetimageurl ( This stringImagePath,stringSize ="_180",stringDefaultPath ="")9         {Ten             if(string. IsNullOrEmpty (ImagePath)) One             { A                 returnDefaultPath; -             } -             //working with picture paths the             varPath = Imagepath.replace ("\\","/"); -             varList = path. Split ('.'); -             if(list. Length >1) -             { +List[list. Length-2] +=size; -             } +             return string. Join (".", list); A}

This method is trickery, the image address stored in the database is generally in this format:

\img\home\logo.png
and the picture server is the size of the resource is a whole set, the default logo.png is the original logo_180.png is small figure logo_420.png is the general M station, app-side size map and so on ...
Let's start with this address backslash:

Get:

/img/home/logo.png
Then, based on the. Split array, the first part of the string is spliced "_180" to get
/IMG/HOME/LOGO_180 is then passed in and PNG. Join together and eventually get:

Here's another way to do this without using array splitting & merging, using the regular method as follows:

1        /// <summary>2         ///use regular match to get the URL of a picture of the specified size3         /// </summary>4         /// <param name= "ImagePath" >picture path E.g:string ImagePath = @ "\img\home\logo.png";</param>5         /// <param name= "Size" >picture size in Resource folder</param>6         /// <param name= "DefaultPath" >Default return path</param>7         /// <returns>formatted picture path E.g:/img/home/logo_180.png</returns>8          Public Static stringGetimageurlbyregex ( This stringImagePath,stringSize ="_180",stringDefaultPath ="")9         {Ten             if(string. IsNullOrEmpty (ImagePath)) One             { A                 returnDefaultPath; -             } -             //working with picture paths theImagePath = Imagepath.replace ("\\","/"); -             //Regular (forward-looking) match conversion size, e.g. replace the matching '. ' with ' _640 ' + '. ' -             stringPattern =@"(\.) (? =jpg|png|bmp)"; -Regex reg =NewRegex (Pattern, regexoptions.ignorecase |regexoptions.multiline); +             returnReg. Replace (ImagePath,string. Format ("{0}{1}", size,"${1}")); -}

The following code decomposition:

String pattern = @ "(\.) (? =jpg|png|bmp) "; This code means a  regular matching rule: Divide the string into two groups of. jpg,. png,. bmp,  and PNG or JPG or BMP
where. Used to match and return,
(=jpg|png|bmp) In this paragraph? = means: Once matched to a string containing '. ' It's not over yet, and you have to go ahead and look at (. The string that follows) whether the containing JPG or PNG or BMP is satisfied, and. After the page match succeeds, the later part is only used for judging and does not return
This allows you to use ${1} to get a match back to the '. '
We will be able to successfully replace the Imgpath in the "_180." , the same gets:

For starters, it doesn't seem that clear, after all, you need to know what "regular looking" and "regular looking back" are.

So, let's start with the basic posture (I've summed up some of the usual regular symbols and added the picture to explain the following):

First recommend a regular expression to explain the site (very practical Oh, you can go inside to see, the interface is very simple) https://regexper.com/input expression, give a graphical explanation

Start looking at the regular symbol: /g global Match / i is case insensitive / M multi-lineYou can write this together./gi global matching and ignoring case-by-casing expressions Two character: 1, Literal literal characters"The original meaning, such as: ABC" 2. Meta character"Non-caption characters in a regular expression with special meaning" include:
  • . Matches any single character except "\ r \ n" such as (http:\/\/www\. +) + (\.com) can match all http:\\www. start. com End URLs
  • ? 0 or 1 times such as: \d?

  • + 1 or more times such as: \d+

  • * 0 or 1 or more times such as: \d*

  • The $ end character, which indicates the end of the expression, such as: \[email protected]$ =[email protected] can match on [email protected], because the end tag is exceeded

  • ^ Start character ^http:\/\/www\. +\.com$ =http://www.baidu.com can match, but http://www.baidu.comm or A/http Www.baidu.com cannot be matched on, although a subset of strings also contains the rules of an expression

  • \ escape character, for example, B is just a character, \b is the meaning of the boundary

    \ \ is the meaning of

  • () grouping , this is better and clearer. The expression between (and) is defined as a group, and the characters that match the expression are saved to a staging area (up to 9 in a regular expression), which can be referenced using \1 to \9 symbols.
      • For example: ^ ([a-za-z]{1,6}) @ (qq|163) (\.com) $

  • The \d number matches a numeric character. equivalent to [0-9]. grep to add-p,perl regular support

  • \d non-numeric matches a non-numeric character. equivalent to [^0-9]. grep to add-pperl regular support

  • \w matches any word character that includes an underscore. Similar but not equivalent to "[a-za-z0-9_]", where the "word" character uses the Unicode character set.

  • \w matches any non-word character. Equivalent to "[^a-za-z0-9_]".

  • {m} {M,n} describes a match appearing m times, or m-n times such as: \w{6}

  • [mn] equals m|n character class, Range class [A-z] closed interval, containing 26 lowercase letters of a and Z

  • \ t matches the tab space on our keyboard

Well, basically commonly used regular symbols are introduced here, because there are many, and when I went to Baidu came out a lump of a lump of, dense, really do not know how to write down spicy, slowly, so I picked up these important and common notes down, I believe the general needs of these are enough to use. But if you want to use a very 6, and efficient, then the effort needs to be studied. Borrow the old adage advocated by Confucianism: "Scientia go, lad."

Today just know that there is a "code snippet" in the function, haha, can not be seen or write too little ah, if not rigorous place also hope that you many forgive, welcome correction!

Mutual encouragement of

--hellocoder December 1, 2016

Getting Started with regular expressions

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.