All Python
#1. Write a Python script to extract all IP addresses from a given text using regular expressions.
input='''Router# show versionCisco Internetwork Operating System Software
IOS (tm) GS Software (RSP-JV-M), Experimental Version 11.1(12816)
[getchell 108]
Copyright (c) 1986-1996 by cisco Systems, Inc.
Compiled Mon 03-Jun-96 11:39 by getchell
Image text-base: 0x600108A0, data-base: 0x60910000
ROM: System Bootstrap, Version 5.3(16645) [szhang 571], INTERIM SOFTWARE
Router uptime is 4 minutes
System restarted by reload
System image file is "slot0:dirt/vip2/master/rsp-jv-mz.960603", booted via tftp from 172.18.2.3
cisco RSP2 (R4600) processor with 24576K bytes of memory.
R4600 processor, Implementation 32, Revision 2.0
Last reset from power-on
G.703/E1 software, Version 1.0.
SuperLAT software copyright 1990 by Meridian Technology Corp).
Bridging software.
X.25 software, Version 2.0, NET2, BFE and GOSIP compliant.
TN3270 Emulation software (copyright 1994 by TGV Inc).
Primary Rate ISDN software, Version 1.0.
Chassis Interface g0/0 129.0.0.1'''
import re
IPs=re.findall('\d+\.\d+\.\d+\.\d+',input)
print(IPs)
#2. Implement a function to validate an email address using regex.
import re
address='mailme@gmail.com'
def validateemail(address):
pattern=r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9]+.[a-zA-Z]{2,}'
match=re.match(pattern,address)
return bool(match)
print(validateemail(address))
#3. Write a function to parse a log file and extract lines that contain a specific keyword.
a='''2025-04-04 10:59:00 INFO Starting application
2025-04-04 11:00:10 ERROR Failed to connect to server
2025-04-04 11:01:20 WARN Disk space running low
2025-04-04 11:02:30 INFO Application stopped'''
def logfile(a):
with open('createfile.txt','w') as f :
f.write(a)
with open('createfile.txt','r') as f:
readfile=f.readlines()
print("File content is ",readfile)
for line in readfile:
pattern=r'ERROR Failed to connect to server'
match=re.findall(pattern,line)
if match:
print(match[0])
else:
print("string not found")
logfile(a)
#4. Implement a function to split a string by multiple delimiters using regex.
import re
text="hello,welcome|to;world:Mine"
def delimiters(text):
pattern=r'[,:;|]'
filter=re.split(pattern,text)
filter1=' '.join(filter)
print(filter1)
delimiters(text)
#5. Write a function to find all URLs in a given text using regular expressions.
text="""
Check out these websites:
https://www.example.com
http://www.testsite.org
Visit our blog at https://blog.example.net for more information.
"""
def urls(text):
pattern = r'[http|https]+://[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.[a-zA-Z]{2,}'
matches=re.findall(pattern,text)
print(matches)
urls(text)
6. #{'s': 1, 'u': 1, 'c': 1, 'h': 1, 'i': 1, 't': 1, 'r': 1, 'a': 1}
from collections import Counter
a='Suchitra Kaunar'
count=dict(Counter(a))
print(count)
char_count={}
for char in a:
if char in char_count:
char_count[char]=+1
else:
char_count[char]=1
print(char_count)
Comments
Post a Comment