Presentation is loading. Please wait.

Presentation is loading. Please wait.

Regular Expressions. 2 3 Using Regular Expressions Regular expressions give you much more power to handle strings in a script. They allow you to form.

Similar presentations


Presentation on theme: "Regular Expressions. 2 3 Using Regular Expressions Regular expressions give you much more power to handle strings in a script. They allow you to form."— Presentation transcript:

1 Regular Expressions

2 2

3 3 Using Regular Expressions Regular expressions give you much more power to handle strings in a script. They allow you to form patterns that can be matched against strings, rather than trying to use the String object’s methods, which are more difficult to be precise with. For example, you may want to know whether the value entered in a text box for an email address included at least one character at the beginning, followed by an at (@) symbol, followed by at least one character, followed by a dot (.), followed by at least two more characters (matching a traditional email address like rex@win.com or the shortest type of email address r@w.us). The String object’s methods don’t provide a neat and clean way to perform this task (although with enough tinkering, it may be possible). However, a regular expression can shorten the task or even turn a match that seemed impossible with the String object’s methods into one that can be completed. http://www.w3schools.com/jsref/jsref_obj_regexp.asp

4 4 Creating Regular Expressions: RegExp Object To create regular expressions, you must create an instance of the JavaScript RegExp object. You can do this almost the same way as you would create a string literal. To create a RegExp literal, you just assign the regular expression to a variable. Instead of using quotation marks to surround the expression, you use forward (/) slashes, as shown here: var varName = /yourPattern/flags; You replace varName with the name you want to use for a variable and replace yourPattern with the regular expression pattern of your choice. You can follow the last slash with one or more flags (which are discussed in upcoming slides). NOTE: JavaScript uses forward slashes to let the browser know that a regular expression is between them, the same way quote marks are used to set off strings. Thus, if a forward slash is used within the regular expression, it must be escaped with a backslash in order to work properly. For instance, instead of writing /02/03/2009/, you would need to write /02\/03\/2009/.

5 5 Creating Regular Expressions CONTINUED The easiest regular expression pattern to create is one that looks for an exact match of characters. For instance, if you wanted to see if the sequence our is present in a string, you could create the following regular expression pattern: var toMatch = /our/; The preceding code creates a RegExp literal named toMatch. Now you need a string against which to test the pattern. If you test the word our against the expression, it’s a match. If you test your, sour, pour, or pouring against it, then it’s a match. If you test cool, Our, oUR, OUR, or souR, then it is not be a match. So how do you perform this test?

6 6 Testing Strings Against Regular Expressions: the test() method To test a regular expression against a string, you can use the test() method of the RegExp object. The basic syntax is as follows: regexName.test(stringToTest); This syntax is similar to using a string method. You replace regexName with the name of the regular expression and replace stringToTest with a string or a string variable name. For instance, look at the following example: var toMatch = /our/; toMatch.test("Kindly pour me another, barkeep!"); This code will test the “Kindly pour me another, barkeep!” string against the regular expression named “toMatch.” It doesn’t use the result, though. So what does it do? The test() method returns a Boolean value of true or false. It returns true when any portion of the string matches the regular expression pattern.

7 7 Testing Strings Against Regular Expressions: the test() method CONTINUED Using the test() method, you can already write a short script, as shown here: var theName = prompt("Enter your name",""); var toMatch = /John/; var isMatch = toMatch.test(theName); if (isMatch) { alert("Wow, we have the same awesome name!"); } else { alert("Not my name, but it works for you!"); } The prompt gathers a name and holds the value in a variable. The pattern to match is John, and it is case sensitive. Thus, only an entry containing John with a capital J followed by lowercase o, h, and n will create a match and return true when it is tested (though it could contain more than just John, so entries such as Johnny or Johnnie or Johnson would also return true—if you want only a specific set of characters, you need to use some additional special characters, which will be discussed a bit later).

8 8 Testing Strings Against Regular Expressions: Adding Flags Flags allow you to make the match case insensitive or to look for every match in the string rather than just the first one (a global test). To add a flag, place it after the last slash in the regular expression. You can use three options, as shown in the table below.

9 9 Testing Strings Against Regular Expressions: Adding Flags CONTINUED If you wanted to adjust the name script used previously to be case insensitive, you could add an i flag to the regular expression, as shown in the following code: var theName = window.prompt("Enter your name",""); var toMatch = /John/i; // the i flag here makes the r.e. case insensitive var isMatch = toMatch.test(theName); if (isMatch) { window.alert("Wow, we have the same awesome name!"); } else { window.alert("Not my name, but it works for you!"); } The test() method will now return true as long as the pattern of John is in the string. It can be in any case, so now John, JOHN, john, and even JoHn are all matches and will cause the test() method to return true.

10 10 Testing Strings Against Regular Expressions: Adding Flags CONTINUED You can also use more than one flag or all three flags at once. For example, if you want to have the match be both case insensitive and global (where it grabs each match in the entire string), you could use the following: var theName = window.prompt("Enter your name",""); var toMatch = /John/ig; // Two flags, i and g var isMatch = toMatch.test(theName); if (isMatch) { window.alert("Wow, we have the same awesome name!"); } else { window.alert("Not my name, but it works for you!"); }

11 11 Creating Powerful Patterns for Regular Expressions Although it’s nice to be able to create such an exact pattern, you won’t always be looking for a match that is so precise. In many cases, you will be looking to match a more general pattern, such as an entry that needs to have at least three characters or that needs to have two characters of any type followed by a special character. By using special characters in your expressions, you can create the type of patterns you need to match a given sequence you want. JavaScript regular expressions use the syntax of Perl regular expressions as a model (if you’ve used regular expressions in Perl, much of this material will be familiar.Perl

12 12

13  Short description, in English  This is what 'governs' the question  A couple of concrete examples to illustrate SOME possible examples  A subset of that table on the prior page, with the 'Example' column removed  There will be "un-useful" entries kept in 13

14 14 Creating Powerful Patterns for Regular Expressions CONTINUED Having had a look at the two tables on the previous slide and the boatload of special characters that are available to you, you can see there are extensive options for creating just about any pattern you need while using regular expressions. And don't freak out! Nobody—okay, maybe there's one or two geeks in the developer community who can pull these things out of thin air—can remember more than just a handful of these, and all developers (especially myself!) need to consult regular expression tables (by "Googling" them) in order to piece together whatever patterns are needed by the program to verify or work with strings.

15 15 Creating Powerful Patterns for Regular Expressions CONTINUED Example: reg_expression_1.html Here's some an example how this works. Let's say you want to make sure a text field contains one or more digits, you could use the \d and + characters with the following HTML and JavaScript code, starting with the HTML code: Enter some text: Next, the JavaScript code: var testButton = document.getElementById("btn1"); testButton.onclick = function() { var hasNum = document.getElementById("hasDigits").value; var toMatch = /\d+/; if(toMatch.test(hasNum)) { window.alert("Your entry contained one or more numbers!"); } else { window.alert("Your entry did not contain any numbers!"); }

16 16 Creating Powerful Patterns for Regular Expressions CONTINUED This code simply checks to see whether any digits are in the string. var toMatch = /\d+/; Here's what it means: The first / and last / forward-slashes lets the code know this is a regular expression the \d finds a match if there is at least a one numeric character in the entry the + finds a match if there is more than one numerical characters in the entry

17 17 Creating Powerful Patterns for Regular Expressions CONTINUED Example: reg_expression_2.html If you want to ensure that the viewer typed in only digits without any other types of characters, you need to be sure the regular expression is written to test from the beginning to the end of the string. Using the ^ and $ symbols you can ensure that the string is tested for the match starting at the beginning of the string and ending at the end of the string. Thus, the following patterns would allow only digits: var toMatch = /^\d+$/; The first / and last / lets the code know this is a regular expression The ^ matches at the beginning of the entry (if we removed the ^ it could have a non-numeric character at the beginning but not at the end) the \d matches if there is at least one numeric character the + matches if there is more than one numerical characters the $ matches at the end of the entry (if we removed the $ it could have a non-numeric character at the end but not at the beginning) Since the only valid characters from the beginning to the end of the string are digits, this will return true only for entries containing digits without other characters present in the string.

18 18 Grouping Regular Expressions Example: reg_expression_3a.html, _3b, _3c You will notice in the regular expression tables above that an expression surrounded by parentheses indicates a group that can be stored for later use in the expression (or using a method such as the match() method where it will store each match of a group along with the overall match in an array). For example, you might decide to use a particular sequence of numbers and to have that sequence repeat a particular number of times. To match the number of times something is repeated, you can use curly brackets {} along with a number or number range. For instance, if you want to match five instances of the number 3, you could use the following expression: /3{5}/ If you wanted this to be a match if the number 3 occurs at least five times but no more than eight times, you could use the following expression: /3{5,8}/ [Note: this one might not be supported by your browser] Now, suppose you wanted the match to start with a 3 and have any digit as the next character, and wanted to match that entire sequence five times (thus, something like 3234353637 would be a match). You might write the following: /(3\d){5}/ [this is grouping the 3 with a second digit sequence 5 times]

19 19 The replace() Method To replace information in a string, you can use regular expressions and the replace() method of the String object. The syntax for using the replace() method is as follows: varName= stringName.replace(regex,newRtring); You replace varName with the name of the variable that will hold the new string value once the information has been replaced. You replace stringName with the name of the string variable that will undergo the replacement. You replace regex with the name of the regular expression to be used to match against the string. Finally, you replace newString with the string or string variable to replace any matched values in the string. http://www.w3schools.com/jsref/jsref_replace.asp

20 20 The replace() Method CONTINUED As an example, the following code replaces the first instance of “car” in myString with “skunk”: var myString = "I like the way a new car smells, and cars are fun."; var toReplace = /car/; var newString = myString.replace(toReplace,"skunk"); window.alert(newString); The preceding code replaces only the first instance of car, giving the alert “I like the way a new skunk smells, and cars are fun.” If you want to change every instance of “car” instead, the g flag is helpful at the end of the regular expression, as shown in the following code: var myString = "I like the way a new car smells, and cars are fun."; var toReplace = /car/g; var newString = myString.replace(toReplace,"skunk"); window.alert(newString); The g flag will match every instance of the regular expression it finds in the string. The viewer will see this alert: “I like the way a new skunk smells, and skunks are fun.”

21 21 The replace() Method CONTINUED You could also use the replace() method to make a name-changing script that is shorter and somewhat less complex than the charat_substring.html example in last lecture's Example Files. By using the replace() method with a regular expression, the first letter of the first and last name can be changed more easily. The following code shows how: function getName() { var toMatch = /^[A-Za-z]+\s[A-Za-z]+$/; var toReplace = /\b[A-Za-z]/gi; var theName = window.prompt("Enter your first and last name",""); if (toMatch.test(theName)) { newName = theName.replace(toReplace,"Z"); window.alert("Now your name is " + newName); } else { window.alert("Name invalid. Please Try Again"); getName(); } getName();

22 22 The match() Method The match() method compares a regular expression and a string to see whether they match. It returns an array containing one or more matches, depending on how it is used. If no match is found, it returns –1. The basic use of the match() method is as follows: string.match(regex); The string will be your string literal, and regex will be your regular expression literal. Note the difference in the order between this method and the test() method. You could use it in this way: var myString = "I am Ironman!"; var toMatch = /Iron/; if (myString.match(toMatch)) { window.alert("The string contains Iron!"); } else { window.alert("Sorry, no Iron in the string."); } If this is used with the g flag or with grouping using (), it will remember each match made (including matches on groups or nested groups) and return each match as an array element.

23 23 The search() Method The search() method executes the search for a match between a regular expression and a specified string. If a match is found, it returns the position in the string where the beginning of the match was found. Otherwise, it returns –1. Here is an example of this method in action: var myString = "I am Ironman!"; var toMatch = /Iron/; if (myString.search(toMatch)) { window.alert("Iron found at position "+ myString.search(toMatch) + "!"); } else { window.alert("Sorry, no Iron found in the string."); } As you can see, the syntax is much like that of the match() method.

24 24 Recommended Links Premier Site about Regular Expressions: http://www.regular-expressions.info/http://www.regular-expressions.info/ Mozilla Site: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressionshttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions Regular Expression Patterns: http://www.javascriptkit.com/javatutors/redev2.shtmlhttp://www.javascriptkit.com/javatutors/redev2.shtml VisiBone Regular Expressions Cheat Sheets: http://www.visibone.com/regular-expressions/http://www.visibone.com/regular-expressions/ EloquentJavaScript: http://eloquentjavascript.net/chapter10.htmlhttp://eloquentjavascript.net/chapter10.html JavaScript Info: http://javascript.info/tutorial/regular-expressions-javascripthttp://javascript.info/tutorial/regular-expressions-javascript Regular Expression Tester: http://regexpal.com/http://regexpal.com/

25  Open a browser; while the site operates in all browsers, it works more efficiently from Firefox or Chrome  Go to https://cascadia.campuslabs.com/courseeval/https://cascadia.campuslabs.com/courseeval/  Enter your username and password  Select the class from the drop down menu  Click on the start evaluation button  Fill out and submit the survey 25


Download ppt "Regular Expressions. 2 3 Using Regular Expressions Regular expressions give you much more power to handle strings in a script. They allow you to form."

Similar presentations


Ads by Google