Skip to content

Instantly share code, notes, and snippets.

@dubeyji10
Forked from MishraKhushbu/regex.py
Created June 22, 2022 06:58
Show Gist options
  • Save dubeyji10/a69c93eaf47ce720be4704117fe8c043 to your computer and use it in GitHub Desktop.
Save dubeyji10/a69c93eaf47ce720be4704117fe8c043 to your computer and use it in GitHub Desktop.
Regular expression
,Regex summary and examples
. - any charcter except newline
\d - Digit(0-9)
\D - Not a digit(0-9)
\w - word charcter(a-z, A-Z,0-9,_)
\W- not a word charcter
\s - whitespace(space , tab, newline)
\S - not a whitespace(space , tab , newline)
\b - word boundry
\B - not a word boundry
^ - begining of a string
$ - end of string
[] - matches character in the bracket
[^ ]- matches charcter Not in the bracket
| - Either or
() - Group
Quantifiers
* - 0 or more
+ - 1 or more
? - 0 or one
{3} - only particular char
{3-4} - range of characters
. and \S works the same all characters or any characters
Examples:
--------------------------------------------
[email protected] y
[email protected]
[email protected]
^\w+(.|-)\w+(.|-)\w+[.|@]\w+[.|-]\w+.\w+[To fetch all above 3 or ]
[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+
-----------------------------------------------------------
https://www.google.com
httpa://coreyms.com
http://youtube.com
https://www.nasa.gov
For above 3 url 1)[a-zA-Z]+2)[:]\/+3)[a-zA-Z.]+
1 for everything before :
2 for everything b/w : and //
3.for rest all
*******************************************
Further work :read regex to match the words in reverse order
****************************************
Difference between re.match re.search re.fullmatch re.find re.findall re.finditer
re.match -->will attempt at the very first match (e.g re.match(r'abc','abcdefgabc') ==>it will give one group)
re.fullmatch --> will attempt the match for the entire string(e.g re.fullmatch(r'abc','abcdefgabc') ==>it will give two groups)
re.search -->will attempt the pattern through out the string
re.findall-->will attempt to search for pattern in the string and returns the result in a list of tuples
re.finditer -->will attept for loop
Link - https://www.youtube.com/watch?v=K8L6KVGG-7o&t=393s (Python Tutorial: re Module - How to Write and Match Regular Expressions (Regex))
Find IP address in a file or MAC
import re
print "Hello World!\n"
a = "fjmgdlmgn %10.12.32.12 iefjmvfkfkbm kb 2A.23.EE.TT"
p = re.findall("\w{2}\.\w{2}\.\w{2}\.\w{2}",a)
print(p)
ouyput
$python main.py
Hello World!
['10.12.32.12', '2A.23.EE.TT']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment