Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Use the Python Regular Expression sub() function to write regular expressions th

ID: 3916768 • Letter: U

Question

Use the Python Regular Expression sub() function to write regular expressions that match following:

(a) Any type of variable name in Perl.

(b) Any IP address (for example, 192.168.1.200).

(c) A user name composed of between 3 to 16 letters, digits, underscores, and minus characters, each stored on a single line in a text file.

(d) Detect any whitespace (space or tab characters) at the beginning of a line.

(e) An integer with an optional sign (either positive or negative)

(f) A C-style hexadecimal number (for example, 0x0AD8f)

Explanation / Answer

"""Use the Python Regular Expression sub() function to write regular expressions that match following: # (a) Any type of variable name in Perl. (b) Any IP address (for example, 192.168.1.200). (c) A user name composed of between 3 to 16 letters, digits, underscores, and minus characters, each stored on a single line in a text file. (d) Detect any whitespace (space or tab characters) at the beginning of a line. (e) An integer with an optional sign (either positive or negative) (f) A C-style hexadecimal number (for example, 0x0AD8f) """ import re ip_pattern = r'^([1-2][0-5][0-9].[1-2]?[0-9]?[0-9].[1-2]?[0-9]?[0-9].[1-2]?[0-9]?[0-9])$' perl_variable_pattern = r'[$@%](w|d)+' #matching $ for var, @ for array and % for hash userName_pattern = r'[a-zA-Z0-9_-]{3,16}' #character length between 3 and 16 consisting of alphabets, digit , underscore and minus whiteSpace_pattern = r'^[s| ]+' # intital space or tab integer_patern = r'[-|+]?d+' #optional sign hex_pattern = r'0[x|X][0-9A-F]+' #hexadecimal number result = re.sub(ip_pattern, "MATCHED", "255.244.89.78") print(result) result = re.sub(perl_variable_pattern, "MATCHED", "$var @array %hash 123 test") print(result) result = re.sub(userName_pattern, "MATCHED", "abc134_ a_1344, a, 13") print(result) result = re.sub(whiteSpace_pattern, "MATCHED", " abc") print(result) result = re.sub(integer_patern, "MATCHED", "134 -144 -q +34") print(result) hex_pattern = r'0[x|X][0-9A-F]+' #hexadecimal number result = re.sub(hex_pattern, "MATCHED", "0x0AD8f 0x0AD8f1, 0xK0AD8fK, mnop") print(result)