Java Reference
In-Depth Information
simple regular expressions
Defining patterns of characters using regular expression syntax can get fairly complex. In this section
you explore just the basics of regular expression patterns. The best way to do this is through examples.
Let's start by looking at an example in which you want to do a simple text replacement using the
replace() method and a regular expression. Imagine you have the following string:
var myString = "Paul, Paula, Pauline, paul, Paul";
and you want to replace any occurrence of the name “Paul” with “Ringo.”
Well, the pattern of text you need to look for is simply Paul . Representing this as a regular
expression, you just have this:
var myRegExp = /Paul/;
As you saw earlier, the forward‐slash characters mark the start and end of the regular expression.
Now let's use this expression with the replace() method:
myString = myString.replace(myRegExp, "Ringo");
You can see that the replace() method takes two parameters: the RegExp object that defines the
pattern to be searched and replaced, and the replacement text.
If you put this all together in an example, you have the following:
<!DOCTYPE html>
 
<html lang="en">
<head>
<title>Chapter 6, Figure 2</title>
</head>
<body>
<script>
var myString = "Paul, Paula, Pauline, paul, Paul";
var myRegExp = /Paul/;
 
myString = myString.replace(myRegExp, "Ringo");
alert(myString);
</script>
</body>
</html>
You can save and run this code. You will see the screen shown in Figure 6-2.
You can see that this has replaced the first occurrence of Paul in your string. But what if you wanted
all the occurrences of Paul in the string to be replaced? The two at the far end of the string are still
there, so what happened?
By default, the RegExp object looks only for the first matching pattern, in this case the first Paul , and then
stops. This is a common and important behavior for RegExp objects. Regular expressions tend to start at
one end of a string and look through the characters until the first complete match is found, then stop.
 
Search WWH ::




Custom Search