Skip to content

Commit 3138d5f

Browse files
committed
two hello world regex examples
1 parent 4d09b8c commit 3138d5f

File tree

3 files changed

+47
-19
lines changed

3 files changed

+47
-19
lines changed

week2_regex/regex_node/regex_helloworld.js

Lines changed: 0 additions & 19 deletions
This file was deleted.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
2+
// Demonstrates exec() in RegExp
3+
4+
var text = "This is a test of regular expressions.";
5+
var regex = /test/;
6+
7+
// The function exec() executes a search for a match in string. the result is an array.
8+
var results = regex.exec(text);
9+
10+
console.log('The match found in the text is: ' + results[0]);
11+
console.log('And the index where it was found: ' + results.index);
12+
console.log('And the input text in case you forgot: ' + results.input);
13+
14+
// And again with capturing parentheses, the global flag, and a loop
15+
text = "Now another test including phone numbers: 212-555-1234 and 917-555-4321 and 646.555.9876.";
16+
// Note the use of 'g' for global matches
17+
regex = /(\d+)[-.]\d+[-.]\d+/g;
18+
19+
while ((results = regex.exec(text)) != null) {
20+
console.log('The full match found in the text is: ' + results[0]);
21+
console.log('Group 1 of the match is: ' + results[1]);
22+
console.log('And the index where it was found: ' + results.index);
23+
// console.log('And the input text in case you forgot: ' + results.input);
24+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
// Demonstrates match() in String
3+
4+
var text = "This is a test of regular expressions.";
5+
var regex = /test/;
6+
7+
// The function match() executes a search for a match in string.
8+
// The result, just like with exec(), is an array.
9+
var results = text.match(regex);
10+
11+
console.log('The match found in the text is: ' + results[0]);
12+
console.log('And the index where it was found: ' + results.index);
13+
console.log('And the input text in case you forgot: ' + results.input);
14+
15+
// Now capturing parentheses and the global flag match() works differently
16+
// Note we can't actually get group 1 this way
17+
text = "Now another test including phone numbers: 212-555-1234 and 917-555-4321 and 646.555.9876.";
18+
regex = /(\d+)[-.]\d+[-.]\d+/g;
19+
20+
results = text.match(regex);
21+
for (var i = 0; i < results.length; i++) {
22+
console.log('Match ' + i + ': ' + results[i]);
23+
}

0 commit comments

Comments
 (0)