Java Reference
In-Depth Information
With the knowledge of boundary matchers, you can rewrite the previous example to
match only integers in the input text:
var pattern = /\b\d+\b/g;
var text = "This is text123 which contains 10 and 120";
var result;
while((result = pattern.exec(text)) !== null) {
print("Matched '" + result[0] + "' at " + result.index +
". Next match will begin at " + pattern.lastIndex);
}
Matched '10' at 31. Next match will begin at 33
Matched '120' at 38. Next match will begin at 41
The String object has a replace(regExp, replacement) method that you can use
to perform find-and-replace operation in text. The following code finds all occurrences of
the word apple in text and replaces it with the word orange :
var pattern = /\bapple\b/g;
var text = "I have an apple and five pineapples.";
var replacement = "orange";
var newText = text.replace(pattern, replacement);
print("Regular Expression: " + pattern + ", Input Text: " + text);
print("Replacement Text: " + replacement + ", New Text: " + newText);
Regular Expression: /\bapple\b/g, Input Text: I have an apple and five
pineapples.
Replacement Text: orange, New Text: I have an orange and five pineapples.
You can treat multiple characters as a unit by using them as a group. A group
is created inside a regular expression by enclosing one or more characters inside
parentheses. (ab) , ab(z) , ab(ab)(xyz) , and (the((is)(are))) are examples of groups.
Each group in a regular expression has a group number. The group number starts at
1. A left parenthesis starts a new group. You can back-reference group numbers in a
regular expression. Suppose that you want to match text, which starts with ab followed
by xy , which is followed by ab . You can write the regular expression as /abxyab/ . You
can also achieve the same result by forming a group that contains ab and back-reference
it as /(ab)xy\1/ , where \1 refers to group 1, which is (ab) in this case. Notice that
the returned Array object from the exec() method of the RegExp object contains the
matched text in the first element and all matched groups in subsequent elements. If you
want to have a group but do not want to capture its result or back reference it, you can
add the character sequence ?: to the beginning of the group; for example, (?:ab)xy
contains a group with the pattern ab , but you cannot reference it as \1 and its matched
text will not be populated in the Array object returned by the exec() method. A group
starting with ?: is called a noncapturing group and a group not starting with ?: is called
 
Search WWH ::




Custom Search