In: Computer Science
For each of the following Perl regular expressions, give a complete and precise description of the function of the regular expression, plus a related example string:
(a) /"([^"]*)"/
(b) /[-+]?\d+(\.\d*)?F\b/
(c) /(\D{2,}).*\[\1\]/
(d) /((.*?)\d)\s\2/
(e) /^[0-9]+\/\d+([+\-*\/]\=|([+]{2}|[-]{2}));$/
Q1) The regular expression /"([^"]*)"/
"([^"]*)"
" " Any text within double inverted commas.
Lets evaluate inside the brackets ( )
^" Anything except " (double inverted comma)
* It is a quantifier. Repetition of the preceding value 0 or any number of times. ie Anything except " (double inverted comma)
Example :
"This is an example"
Q2) The regular expression /[-+]?\d+(\.\d*)?F\b/
[-+]?\d+(\.\d*)?F\b
[-+] Either a minus or plus sign.
[-+]? ? means matches between zero and one times. So there can be minus, plus or no sign.
\d matches a digit (equal to [0-9]).
\d+ digit repeated 1 or unlimited times.
\. matches character . (dot)
\d* digit repeated zero or many times.
(\.\d*)? ? means a decimal value related 0 or 1 time.
F Character F literally
\b Matches word boundary. it means it has to end with F
This expression represent a negative or positive Fahrenheit value
Example :
-3.54F or +25.66F
Q3) The regular expression /(\D{2,}).*\[\1\]/
(\D{2,}).*\[\1\]
\D Anything but not digit 0-9.
\D{2,} Anything but not digit 0-9 matching 2 or more times ie two or more anything but not digits. Can be 2 characters like KR
.* matches any character but not end of line \n ie it shouldn't stop with KR alone
\[ \] means square brackets [ ]
\1 matches the same text as most recently matched by (\D{2,}) ie 1st two characters, in our example KR
Example :
GABV[GA] : True
GABV dd[GA] : True
GBV[GA] : False
Q4) The regular expression /((.*?)\d)\s\2/
(.*?)\d)\s\2
(.*?) matches any character (except for line terminators) zero or unlimited times.
\d matches a digit (equal to [0-9]).
\s matches any whitespace character like a tab or enter.
\2 ((.*?)\d) is call the 1st group. and (.*?) is the 2nd group. \2 means match the 2nd group (.*?) ie characters 0 or more times
Any thing text or no text followed by a digit then a white space followed by text or no text.
Example :
I am 6 years old