1 / 65

Regular Expressions

Regular Expressions. Regex Links. MDN Regular Expressions Regexpal. Regular Expressions. Patterns used to match character combinations in strings. In JS, regular expressions can be used with the RegExp object and with the String object. . Regex Use Cases.

alain
Télécharger la présentation

Regular Expressions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Regular Expressions CSE 3345

  2. Regex Links • MDN Regular Expressions • Regexpal

  3. Regular Expressions • Patterns used to match character combinations in strings. • In JS, regular expressions can be used with the RegExpobject and with the String object. CSE 3345

  4. Regex Use Cases • Find and extract data from a document. • Validate content supplied in a form before it is submitted. • Telephone numbers • SSN • Email addresses • Anything that follows a pattern CSE 3345

  5. Regex Syntax • Regular expressions are an extremely powerful tool implemented in most languages; however… • Regular expressions have their own syntax and usage of special characters. • Difficult to remember if you use them infrequently. CSE 3345

  6. Regex Special Characters: ^ Regex: ^A Matches: “Aaaann Animal Named Alex” Doesn’t match: “an A” CSE 3345

  7. Regex Special Characters: $ Regex: t$ Matches: “Today I ate a tart” Doesn’t match: “tart is here” CSE 3345

  8. Regex Special Characters: * Regex: a* Matches: “aaaaaaaaaaaaaallred” Matches: “tart” Doesn’t match: “tom” //Star and Question Mark Characters are useful for the patterns with some variation. Regex: a*m Matches: “tom” *Novice users often overuse/misuse this character.* CSE 3345

  9. Regex Special Characters: + Regex: 1+ Matches: “911” Matches: “912” Doesn’t match: “8675309” CSE 3345

  10. Regex Special Characters: ? Regex: l? Matches: “lily” Matches: “llog” Doesn’t match: “Ron” CSE 3345

  11. Regex Special Characters: . Regex: .n Matches: “nay, an apple is on the tree” Doesn’t match: “nay, an apple is on the tree” CSE 3345

  12. Regex Special Characters: | Regex: red|blue Matches: “hand me that blue crayon” Matches: “hand me that red crayon” Doesn’t match: “hand me that black crayon” CSE 3345

  13. Regex Syntax: {n} Regex: a{2} Matches: “Caandy” Matches: “Caaandy” Doesn’t match: “Candy” CSE 3345

  14. Regex Syntax: {n,m} Regex: a{1,3} Matches: “Candy” Matches: “Caaandy” Matches: “Caaaandy” Doesn’t match: “Cndy” CSE 3345

  15. Regex Syntax: [xyz] Regex: [a-d] Matches: “candy” Matches: “brisket” CSE 3345

  16. Regex Syntax: [xyz] Regex: [0-5] Matches: “0123456789” Matches: “543210” CSE 3345

  17. Regex and Javascript CSE 3345

  18. Sample Regex • To use a regex in javascript, surround the regex with forward slashes • For example, I have the regex [a-z]. To use it in javascript I would do the following. var regex =/[a-z]/;//matches any lower case character that is in the alphabet a-z. var string ="tom"; string.match(regex);// ["t"] CSE 3345

  19. Advanced Regex Flags Regular expression have four optional flags that allow for global and case insensitive searching. These flags can be used separately or together in any order, and are included as part of the regex. CSE 3345

  20. Advanced Regex Flags Example "tom".match(/T/);// null //Using the i flag you can perform case insensitive searches. "tom".match(/T/i);// ["t"/ CSE 3345

  21. Regex Challenge • Write a regular expression that will only accept a string that contains • lower and upper case alphabet characters • Underscore characters • Must have an inclusive length between 8 and 32. CSE 3345

  22. XMLHttpRequest Reference Links • MDN • Jibbering.com • OpenJSXMLHttpRequest Example CSE 3345

  23. AJAX Quickfacts • Using the XMLHttpRequest API is what is known as AJAX. • Asynchronous Javascript and XML. • Used to send data back and forth from client to server without leaving a webpage. CSE 3345

  24. AJAX Quick facts • AJAX is the combination of HTML, CSS, and Javascript. • Makes sending HTTP request fast and easy. • Wasn’t very popular until Microsoft’s Outlook Web Access (2000) and Google’s Google Maps(2005) and Gmail(2004). CSE 3345

  25. How AJAX Works CSE 3345

  26. Creating an XMLHttpRequest() • Older browsers, IE5 and IE6, use a different method. • Newer browsers do the following: varrequest =newXMLHttpRequest(); CSE 3345

  27. Initialize a request • Use the open() method to initialize a request. //open() interface voidopen(DOMStringmethod, DOMStringurl, optional booleanasync, optional DOMString user, optional DOMString password ); CSE 3345

  28. open() : Required Parameters • method - The HTTP method to use, such as "GET", "POST", "PUT", "DELETE", etc. • url - The URL to which to send the request. CSE 3345

  29. open() : Optional Parameters • async - An optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. If this value is false, the send()method does not return until the response is received. • user - The optional user name to use for authentication purposes; by default, this is an empty string. • password - The optional password to use for authentication purposes; by default, this is an empty string. CSE 3345

  30. open() example var request =newXMLHttpRequest(); request.open("GET","www.google.com",false); CSE 3345

  31. Send the request var request =newXMLHttpRequest(); request.open("GET","www.google.com",false); request.send(); CSE 3345

  32. Handling a response message • When the server receives the client request, it will perform any necessary actions and return back to the client a response message. • In most cases, the only handling required is to check the response status code, and if everything is okay access the responseText. CSE 3345

  33. Handling a response message var request =newXMLHttpRequest(); request.open("GET","www.google.com",false); request.send(); if(request.status===200){//200 is an HTTP status code. console.log(request.responseText);//print resp txt to console } CSE 3345

  34. Response Messages attributes/methods • status – returns HTTP Status code • statusText – returns HTTP status text • getResponseHeader() – get specified header from response message. • getAllResponseHeaders() – get all headers from response message. CSE 3345

  35. Handling a response message • responseType – returns the format the response is in: "arraybuffer", "blob", "document", "json", and "text“. • response – returns of the response entity body. • responseText – returns the text of the response entity body. • responseXML – returns a DOM object of an xml document. CSE 3345

  36. Your Turn • Using this fiddle as basis, make an XMLHttpRequest to http://lyle.smu.edu/~craley/3345/http/showResponse.php. CSE 3345

  37. Using Query Parameters • If you recall, GET and POST requests can send a key-value name pair along with an HTTP request. • This is useful for adding query parameters to your request. CSE 3345

  38. Query Parameters Example A typical example would look like this: name=Tim&lastname=Drake&age=17&alias=Robin CSE 3345

  39. GET Request • When sending a GET request, you combine the urlwith query parameters separated by a question mark. http://www.google.com?name=Tim&lastname=Drake&age=17&alias=Robin CSE 3345

  40. GET Request with Query Parms in JS varurl='http://www.google.com'; varparms='name=Tim&lastname=Drake&age=17&alias=Robin'; request.open('GET',url+"?"+parms,false); request.send(); CSE 3345

  41. POST Request • When sending a POST request, the HTTP Message includes the query parameters as apart of the message body. • Additional information about the query parameters are sent as header info: • Content type • Content length • Etc CSE 3345

  42. POST Request with Query Parms in JS varurl='http://www.google.com'; varparms='name=Tim&lastname=Drake&age=17&alias=Robin'; request.open('POST',url,false); //Send the proper header information along with the request. //Depending on the data type (xml, json, etc) you would modify the content type header. request.setRequestHeader("Content-type","application/x-www-form-urlencoded"); request.send(parms); See jsFiddle CSE 3345

  43. Full XMLHttpRequest Example • http://lyle.smu.edu/~craley/3345/http/httpRequest.html CSE 3345

  44. Synchronous Requests • So far we’ve only seen synchronous requests. • These requests pause code execution and wait until a response is given from the server before continuing. • Depending on the request you could be paused for a long time. • Not ideal for practical purposes. CSE 3345

  45. Asynchronous Requests • These requests provide a callback function that is triggered when the server responds. • Code execution isn’t paused. • This is what you should be using in your code. CSE 3345

  46. AsyncXMLHttpRequest Example varurl="http://www.google.com"; var request =newXMLHttpRequest(); request.onreadystatechange=function(){ //readyState === 0 : UNSENT. Means open() hasn't been called //readyState === 1 : OPENED. Means send() hasn't been called //readyState === 2 : HEADERS_RECEIVED. Means send() has been called //and headers have been received //readyState === 3 : LOADING. Means downloading //readyState === 4 : DONE. The operation is complete if(request.readyState===4){ document.body.innerHTML=request.responseText; } } request.open('GET',url,true); request.send(); See jsFiddle CSE 3345

  47. XMLHttpRequest Bummer • Unless you have been given permission, you cannot successfully make an HTTP Request to another server. • Cross Domain Request • Work arounds for this are • Use a different scripting language (PHP, Python) • Use JSONP • If you have access to the different sever, you can get Cross Domain Request permission. CSE 3345

  48. JSON Reference Links • JSONLint – a JSON validator • MDN • JSON.org CSE 3345

  49. JSON Quick facts • JSON – javascript object notation • JSON is a collection of name value pairs • Is a data-exchange format. • Closely resembles Javascript syntax. • Can parse JSON into a JS object. CSE 3345

  50. Hello World JSON Example { “fname" : “bruce" } Object All JSON data starts and ends with a curly brace or square brace The curly brace is what encapsulates the data into an Object. After all, JSON stands for Javascript ObjectNotation. CSE 3345

More Related