Regex Usage Flashcards
-
-
-
incomplete
-
-
-
incomplete
-
-
-
incomplete
-
-
-
incomplete
-
-
-
incomplete
-
-
-
incomplete
What does \1 reference in ([’”]).+?\1
when used on
“adfasd f ‘asdfasd’ as df”
”
When you have multiple capture groups (), how do you know which one a backreference \1 refers to?
What about nested capture groups?
1 and up from left to right (opening parenthesis)
So nested goes in order of opening parenthesis (outer to inner)
isUrl(‘http://launchschool.com’); // -> true
isUrl(‘https://example.com’); // -> true
isUrl(‘https://example.com hello’); // -> false
isUrl(‘ https://example.com’); // -> false
let isUrl = function (text) {
return !!text.match(/^https?:\/\/\S+$/);
};
fields(“Pete,201,Student”);
// -> [‘Pete’, ‘201’, ‘Student’]
fields(“Pete \t 201 , TA”);
// -> [‘Pete’, ‘201’, ‘TA’]
fields(“Pete \t 201”);
// -> [‘Pete’, ‘201’]
fields(“Pete \n 201”);
// -> [‘Pete’, ‘\n’, ‘201’]
let fields = function (str) {
return str.split(/[ \t,]+/);
};
Change first math operator to a ‘?’
mysteryMath(‘4 + 3 - 5 = 2’);
// -> ‘4 ? 3 - 5 = 2’
mysteryMath(‘(4 * 3 + 2) / 7 - 1 = 1’);
// -> ‘(4 ? 3 + 2) / 7 - 1 = 1’
let mysteriousMath = function (equation) {
return equation.replace(/[+-*\/]/, ‘?’);
};
Write a method that changes every arithmetic operator (+, -, *, /) to a ‘?’ and returns the resulting string. Don’t modify the original string.
mysteriousMath(‘4 + 3 - 5 = 2’); // -> ‘4 ? 3 ? 5 = 2’
mysteriousMath(‘(4 * 3 + 2) / 7 - 1 = 1’); // -> ‘(4 ? 3 ? 2) ? 7 ? 1 = 1’
let mysteriousMath = function (equation) {
return equation.replace(/[+-*\/]/g, ‘?’);
};
write a method that changes strings in the date format 2016-06-17 to the format 17.06.2016. You must use a regular expression and should use methods described in this section.
formatDate(‘2016-06-17’); // -> ‘17.06.2016’
formatDate(‘2016/06/17’); // -> ‘2016/06/17’ (no change)
let formatDate = function (original_date) {
return original_date.replace(/^(\d\d\d\d)-(\d\d)-(\d\d)$/, ‘$3.$2.$1’);
};
write a method that changes dates in the format 2016-06-17 or 2016/06/17 to the format 17.06.2016. You must use a regular expression and should use methods described in this section.
(2 ways, one more readable)
formatDate(‘2016-06-17’); // -> ‘17.06.2016’
formatDate(‘2017/05/03’); // -> ‘03.05.2017’
formatDate(‘2015/01-31’); // -> ‘2015/01-31’ (no change)
let formatDate = function (originalDate) {
return originalDate.replace(/^(\d\d\d\d)-(\d\d)-(\d\d)$/, ‘$3.$2.$1’)
.replace(/^(\d\d\d\d)\/(\d\d)\/(\d\d)$/, ‘$3.$2.$1’);
};
or (less readable)
let formatDate = function (originalDate) {
let dateRegex = /^(\d\d\d\d)([-\/])(\d\d)\2(\d\d)$/;
return originalDate.replace(dateRegex, ‘$4.$3.$1’);
};
how does [\S\s] differ from .?
[\S\s] will match newlines