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.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

© Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● / www,histpk.org Hidaya Institute of Science & Technology
FORM VALIDATION Faheem Ahmed Khokhar. FORM VALIDATION Faheem Ahmed Khokhar.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
25-Jun-15 JavaScript Language Fundamentals II. 2 Exception handling, I Exception handling in JavaScript is almost the same as in Java throw expression.
Tutorial 14 Working with Forms and Regular Expressions.
Escaping Characters document.write(). Learning Objectives By the end of this lecture, you should be able to: – Recognize some of the characters that can.
JavaScript, Third Edition
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
CST JavaScript Validating Form Data with JavaScript.
The Registration Experience Student Registration via Self-Service.
Slide 6a-1 CHAPTER 6 Matching Patterns: Using Regular expressions to match patterns.
XP Tutorial 14 New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
Last Updated March 2006 Slide 1 Regular Expressions.
JavaScript Form Validation
1 Chapter 6 – Creating Web Forms and Validating User Input spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
Wednesday, March 5 th, 2014 Instructor: Craig Duckett Scripting Tables and Forms Murach - Chapter 17 Scripting Tables and Forms pp.
Regular Expressions Week 07 TCNJ Web 2 Jean Chu. Regular Expressions Regular Expressions are a powerful way to validate and format text strings that may.
Tutorial 14 Working with Forms and Regular Expressions.
Chapter 6: Forms JavaScript - Introductory. Previewing the Product Registration Form.
Faculty of Sciences and Social Sciences HOPE JavaScript Validation Regular Expression Stewart Blakeway FML
Understanding Mathematical Operators For a mathematical calculation, you use a mathematical operator. The values that you use can be any sort of values.
JavaScript Lecture 6 Rachel A Ober
PHP meets MySQL.
G053 - Lecture 16 Validating Forms Mr C Johnston ICT Teacher
Copyrighted material John Tullis 10/17/2015 page 1 04/15/00 XML Part 3 John Tullis DePaul Instructor
Using Client-Side Scripts to Enhance Web Applications 1.
DHTML AND JAVASCRIPT Genetic Computer School LESSON 5 INTRODUCTION JAVASCRIPT G H E F.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Limits From the initial (HINARI) PubMed page, we will click on the Limits search option. Note also the hyperlinks to Advanced search and Help options.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
CPS120: Introduction to Computer Science Decision Making in Programs.
Submitting Course Outlines for C-ID Designation Training for Articulation Officers Summer 2012.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
CONTENTS Processing structures and commands Control structures – Sequence Sequence – Selection Selection – Iteration Iteration Naming conventions – File.
Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
Regular Expressions for PHP Adding magic to your programming. Geoffrey Dunn
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming regular expressions.
Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizard’s Guide to PHP by David Lash.
CS346 Regular Expressions1 Pattern Matching Regular Expression.
May 2008CLINT-LIN Regular Expressions1 Introduction to Computational Linguistics Regular Expressions (Tutorial derived from NLTK)
Copyright © Curt Hill Regular Expressions Providing a Search Pattern.
Working with Strings. Learning Objectives By the end of this lecture, you should be able to: – Appreciate the need to search for and extract information.
Unit 10 – JavaScript Validation Instructor: Brent Presley.
Validation using Regular Expressions. Regular Expression Instead of asking if user input has some particular value, sometimes you want to know if it follows.
Unit 11 –Reglar Expressions Instructor: Brent Presley.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
XP Tutorial 7 New Perspectives on JavaScript, Comprehensive 1 Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
-Joseph Beberman *Some slides are inspired by a PowerPoint presentation used by professor Seikyung Jung, which was derived from Charlie Wiseman.
OVERVIEW OF CLIENT-SIDE SCRIPTING
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Regular Expressions In Javascript cosc What Do They Do? Does pattern matching on text We use the term “string” to indicate the text that the regular.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
CHAPTER 10 JAVA SCRIPT.
Annual Performance Management Cycle Management Training Tutorial
Regular Expressions 'RegEx'.
Chapter 6 JavaScript: Introduction to Scripting
In this session, you will learn about:
Project 9 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms.
* Lecture # 7 Instructor: Rida Noor Department of Computer Science
Chapter 19 PHP Part II Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Intro to PHP & Variables
Working with Forms and Regular Expressions
While Loops BIS1523 – Lecture 12.
T. Jumana Abu Shmais – AOU - Riyadh
Functions, Regular expressions and Events
BIT116: Scripting Lecture 13
Web Programming and Design
Presentation transcript:

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 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 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 address like or the shortest type of address 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.

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 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 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 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 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 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 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 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

 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 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 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 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 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 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 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 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.

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 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 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 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 Recommended Links Premier Site about Regular Expressions: Mozilla Site: Regular Expression Patterns: VisiBone Regular Expressions Cheat Sheets: EloquentJavaScript: JavaScript Info: Regular Expression Tester:

 Open a browser; while the site operates in all browsers, it works more efficiently from Firefox or Chrome  Go to  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