CS346 Regular Expressions1 Pattern Matching Regular Expression.

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

COS 381 Day 19. Agenda  Assignment 5 Posted Due April 7  Exam 3 which was originally scheduled for Apr 4 is going to on April 13 XML & Perl (Chap 8-10)
Cos 381 Day 4. © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Agenda Exam 1 Corrected –3 A’s, 3 B’s and 2 C’s I have looked at all the assignment.
CS 330 Programming Languages 10 / 10 / 2006 Instructor: Michael Eckmann.
CS 330 Programming Languages 09 / 30 / 2008 Instructor: Michael Eckmann.
Tutorial 14 Working with Forms and Regular Expressions.
Scripting Languages Chapter 8 More About Regular Expressions.
Regular Expressions in ColdFusion Applications Dave Fauth DOMAIN technologies Knowledge Engineering : Systems Integration : Web.
REGULAR EXPRESSIONS CHAPTER 14. REGULAR EXPRESSIONS A coded pattern used to search for matching patterns in text strings Commonly used for data validation.
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.
Tutorial 14 Working with Forms and Regular Expressions.
Lecture 7: Perl pattern handling features. Pattern Matching Recall =~ is the pattern matching operator A first simple match example print “An methionine.
Computer Programming for Biologists Class 5 Nov 20 st, 2014 Karsten Hokamp
Lecture 8 perl pattern matching features
Modern JavaScript Develop And Design Instructor’s Notes Chapter 10 – Working with Forms Modern JavaScript Design And Develop Copyright © 2012 by Larry.
Sys.Prog & Scripting - HW Univ1 Systems Programming & Scripting Lecture 18: Regular Expressions in PHP.
Chapter 4 The Basics of JavaScript. © 2006 Pearson Addison-Wesley. All rights reserved Overview of JavaScript - Originally developed by Netscape,
RegExp. Regular Expression A regular expression is a certain way to describe a pattern of characters. Pattern-matching or keyword search. Regular expressions.
1 CSC 594 Topics in AI – Text Mining and Analytics Fall 2015/16 4. Document Search and Regular Expressions.
Regular Expressions.
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.
PHP with Regular Expressions Web Technologies Computing Science Thompson Rivers University.
BY Sandeep Kumar Gampa.. What is Regular Expression? Regex in.NET Regex Language Elements Examples Regular Expression API How to Test regex in.NET Conclusion.
Regular Expressions in PHP. Supported RE’s The most important set of regex functions start with preg. These functions are a PHP wrapper around the PCRE.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 24 The String Section.
DHTML1-1 JavaScript and HTML Documents Xingquan (Hill) Zhu
VBScript Session 13.
Overview A regular expression defines a search pattern for strings. Regular expressions can be used to search, edit and manipulate text. The pattern defined.
Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
When you read a sentence, your mind breaks it into tokens—individual words and punctuation marks that convey meaning. Compilers also perform tokenization.
Regular Expressions for PHP Adding magic to your programming. Geoffrey Dunn
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming regular expressions.
JavaScript, Part 2 Instructor: Charles Moen CSCI/CINF 4230.
Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizard’s Guide to PHP by David Lash.
12. Regular Expressions. 2 Motto: I don't play accurately-any one can play accurately- but I play with wonderful expression. As far as the piano is concerned,
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
CS 330 Programming Languages 10 / 02 / 2007 Instructor: Michael Eckmann.
1 Perl, Beyond the Basics: Regular Expressions, Subroutines, and Objects in Perl CSCI 431 Programming Languages Fall 2003.
Copyright © Curt Hill Regular Expressions Providing a Search Pattern.
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
JavaScript III ECT 270 Robin Burke. Outline Validation examples password more complex Form validation Regular expressions.
CIT 383: Administrative ScriptingSlide #1 CIT 383: Administrative Scripting Regular Expressions.
1 Validating user input is the bane of every software developer’s existence. When you are developing cross-browser web applications (IE4+ and NS4+) this.
Java Script Pattern Matching Using Regular Expressions.
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.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607.
Standard Types and Regular Expressions CS 480/680 – Comparative Languages.
Prof. Alfred J Bird, Ph.D., NBCT Door Code for IT441 Students.
INT222 – Internet Fundamentals Week 11: RegExp Object and HTML5 Form Validation 1.
Chapter 4 © 2013 by Pearson Overview of JavaScript - Originally developed by Netscape, as LiveScript - Became a joint venture of Netscape and Sun.
Introduction to Programming the WWW I CMSC Winter 2004 Lecture 13.
XP Tutorial 7 New Perspectives on JavaScript, Comprehensive 1 Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
An Introduction to Regular Expressions Specifying a Pattern that a String must meet.
Chapter 4 © 2009 by Addison Wesley Longman, Inc Pattern Matching - JavaScript provides two ways to do pattern matching: 1. Using RegExp objects.
Pattern Matching: Simple Patterns. Introduction Programmers often need to scan a file, directory, etc. for a specific substring. –Find all files that.
CS 330 Programming Languages 09 / 30 / 2008 Instructor: Michael Eckmann.
CS 330 Class 7 Comments on Exam Programming plan for today:
Chapter 6 JavaScript: Introduction to Scripting
CSC 594 Topics in AI – Natural Language Processing
Regular Expressions and perl
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 ©
SEEM4570 Tutorial 05: JavaScript as OOP
CSC 594 Topics in AI – Natural Language Processing
Working with Forms and Regular Expressions
CSCI 431 Programming Languages Fall 2003
Functions, Regular expressions and Events
- Regular expressions:
Lecture 23: Regular Expressions
Presentation transcript:

CS346 Regular Expressions1 Pattern Matching Regular Expression

CS346 Regular Expressions2 Pattern Matching JavaScript provides two ways to do pattern matching: 1. Using RegExp objects 2. Using methods on String objects  RE in both ways are the same  Same as in Perl

CS346 Regular Expressions3 Simple patterns Two categories of characters in patterns: a. normal characters (match themselves) b. metacharacters (can have special meanings in patterns--do not match themselves) \ | ( ) [ ] { } ^ $ * + ?. - A metacharacter is treated as a normal character if it is backslashed - period (.) is a special metacharacter - it matches any character except newline

CS346 Regular Expressions4 create RegExp objects  var varname = / reg_ex_pattern / flags  Simplest example: exact match  To match occurrence of “our” in a string containing your, our, sour, four, pour  var toMatch = /our/;

CS346 Regular Expressions5 1. Matching in RegExp objects  Tests a string for pattern matches. This method returns a Boolean that indicates whether or not the specified pattern exists within the searched string. This is the most commonly used method for validation. Use test() method of RegExp object Format: regexp.test( string_to_be_tested )  test() returns a Boolean var tomatch=/our/; var result = tomatch.test(“pour”); //boolean result Example: 16-0-checkName.html

CS346 Regular Expressions6 Pattern Modifiers (Adding flags) Flag(s)Purpose iMakes the match case insensitive /oak/i matches "OAK" and "Oak" gPerforms a global match not just the first igMakes the match case insensitive and global

CS346 Regular Expressions7 2. Matching in Strings  search() method Returns the position in the specified string of the RE pattern (position is relative to zero); returns -1 if it fails var str = "Gluckenheimer"; var position = str.search(/n/); /* position is now 6 */  match() method compares a RE and a string to see whether they match.  replace() method finds out if a RE matches a string and then replaces a matched string with a new string

CS346 Regular Expressions8 search() method  Format: string.search(reg-exp) Searches the string for the first match to the given regular expression returns an integer that indicates the position in the string (zero-indexed). If no match is found, the method will return –1.  Similar to the indexOf() method,  Example: To find the location of the first absolute link within a HTML document:: pos = htmlString.search(/^<a href = ” if ( pos != -1) { alert( ‘First absolute link found at’ + pos +’position.’); } else { alert ( ‘Absolute links not found’); }

CS346 Regular Expressions9 Match() method  match() method  Format: string.match( regular_expression )  returns an array of all the matching strings found in the string given. If no matches are found, then match() returns false.  Example: To check the proper format for a phone number entered by a user, with the form of (XXX) XXX-XXXX.  function checkPhone( phone ) { phoneRegex = /^\(\d\d\d\) \d\d\d-\d\d\d\d$/; if( !phone.match( phoneRegex ) ) { alert( ‘Please enter a valid phone number’ ); return false; } return true; }

CS346 Regular Expressions10 replace() method  Format string.replace(reg_exp)  Properties: replaces matches to a given regular expression with some new string.  Example: To replace every newline character (\n) with a break tag, comment = document.forms[0].comments.value; /* assumes that the HTML form is the first one present in the document, and it has a field named “comments” */ comment = comment.replace( /\n/g, “ ”); function formatField( fieldValue ) { return fieldValue = fieldValue. replace(/\n/g, “ ”); }  The function accepts any string as a parameter, and returns the new string with all of the newline characters replaced by tags.

CS346 Regular Expressions11 Character classes – [ ]  Sequence of characters in brackets defines a set of characters, any one of which matches  e.g. [abcd]  Dashes used to specify spans of characters in a class  e.g. [a-z]  A caret at the left end of a class definition means  the opposite  e.g. [^0-9]

CS346 Regular Expressions12 Character class abbreviations AbbreviationEquiv. PatternMatches \d[0-9]a digit \D[^0-9]not a digit \w[A-Za-z_0-9]a word char. \W[^A-Za-z_0-9]not a word char. \s[ \r\t\n\f]a whitespace char. \S [^ \r\t\n\f] not a whitespace char.

CS346 Regular Expressions13 From Chapter 25 of text - Perl Note the difference of usage of ^ here and in a class

CS346 Regular Expressions14 Quantifiers Quantifiers in braces - Repetitions QuantifierMeaning {n}exactly n repetitions {m,}at least m repetitions {min, max}at least min but max repetitions allowed

CS346 Regular Expressions15 Some other common Quantifiers *zero or more repetitions e.g., \d* means zero or more digits + one or more repetitions e.g., \d+ means one or more digits ? zero or one e.g., \d? means zero or one digit. exactly one character except newline character e.g., /.l/ matches al but not \n nor l

CS346 Regular Expressions16 Anchors The pattern can be forced to match only at the left end with ^; at the end with $ e.g., /^Lee/ matches "Lee Ann" but not "Mary Lee Ann" /Lee Ann$/ matches "Mary Lee Ann", but not "Mary Lee Ann is nice“ The anchor operators (^ and $) do not match characters in the string--they match positions, at the beginning or end

CS346 Regular Expressions17 Examples  test() See 16-1checkURL.html See 16-2valid .html  search() method in String See 16-3check_phone.html

CS346 Regular Expressions18 replace method()  replace(RE_pattern, string) Finds a substring that matches the pattern replaces it with the string g modifier applicable var str = "Some rabbits are rabid"; str.replace(/rab/g, "tim"); str is now "Some timbits are timid“ Matched substrings stored in $1, $2, etc $1 and $2 are both set to "rab"

CS346 Regular Expressions19 match(pattern)  Most general pattern-matching method Returns an array of results of the pattern-matching operation With the g modifier, returns an array of the substrings that matched Without the g modifier, first element of the returned array has the matched substring, the other elements have the values of $1, … obtained by parenthesized parts of pattern var str = "My 3 kings beat your 2 aces"; var matches = str.match(/[ab]/g); - matches is set to ["b", "a", "a"]

CS346 Regular Expressions20 match(pattern) example 16-4matchExample.html var str = “Having a take-home exam that takes 3 hours to complete is better than a 1-hour in-class exam”; var matches = str.match( /\d/g ); matches is set to [3, 1]

CS346 Regular Expressions21 Parentheses in RE Example: 16-5complexMatchEx.html var str = "I have 118 credits; but I need 120 to graduate"; matches = str.match(/(\d+)([^\d]+)(\d+)/); document.write(matches, " "); 1 st element of matches is the match, 2 nd is the value of $1, 3 rd element $2, 4 th element $3 etc. matches array: 118 credits; but I need 120,118, credits; but I need,120 ______________________ ___ _______________ ___ match with RE $1 $2 $3

CS346 Regular Expressions22 Alternate patterns  Use the alternation operator |  Example: 16-6matchAlternatives.html

CS346 Regular Expressions23 split(parameter) of String splits a string into substrings based on a pattern “:" and /:/ both work Example: 16-7splitEx.html

CS346 Regular Expressions24 Program Structure  Example 16-3check_phone.html  Limitations?  How can you make it more flexible?  Can you generalize it for checking multiple fields

CS346 Regular Expressions25 Uniform Program Structure for multiple tests  regex_name.test( string_to_be_tested ) to test each field  if test() returns false, compile an error message  See 16-8Structure.html

Examples of curly braces { }  16-9-curly_braces.html CS346 Regular Expressions26

CS346 Regular Expressions27 Table – Regular Expression Codes  See “Regular Expression Codes.doc”