Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ################### Python Positive Lookahead ###########################
- # So, in this case, the regular expression is looking
- # for word boundaries (\b), followed by one or more word characters (\w+),
- # but only if they are immediately followed by the substring "ing" ((?=ing)).
- # The result is that it finds and returns the word "cod" from the word
- # "coding" in the input text.
- import re
- text = "I love coding in Python!"
- pattern = r"\b\w+(?=ing)"
- result = re.findall(pattern, text)
- print(result)
- # Output: ['cod']
- print()
- text_2 = "I love coding in Python!"
- pattern_2 = r"(\b\w+\s*)+(?=ing)"
- result_2 = re.search(pattern_2, text_2)
- if result_2:
- print(result_2.group())
- # Output: I love cod
- print()
- text_3 = "Ilovecoding in Python!"
- pattern_3 = r"(\b\w+\s*)*(?=ing)"
- result_3 = re.search(pattern_2, text_3)
- if result_3:
- print(result_3.group())
- # Output: Ilovecod
- print()
- # In this example, the pattern looks for words that are followed by a space
- # and the word "and". The result is the word "bright" because it fulfills
- # the criteria specified by the positive lookahead assertion.
- text_4 = "The future is bright and coding is exciting!"
- pattern_4 = r"\b\w+(?=\sand)"
- result_4 = re.findall(pattern_4, text_4)
- print(result_4)
- # Output: ['bright']
- print()
- text_5 = "Regular expressions are powerful and Python is awesome!"
- pattern_5 = r"\b\w+(?=\sand)"
- result_5 = re.findall(pattern_5, text_5)
- print(result_5)
- # ['powerful']
- print()
- text_6 = "The future is bright and coding is exciting!"
- pattern_6 = r"\b\w+(?=\sand)"
- result_6 = re.findall(pattern_6, text_6)
- print(result_6)
- # ['bright']
- print()
- text_7 = "Positive thinking leads to positive outcomes."
- pattern_7 = r"\b\w+(?=\sthinking)"
- result_7 = re.findall(pattern_7, text_7)
- print(result_7)
- # ['Positive']
- print()
- text_8 = "1 Python is about 4 feet long"
- pattern_8 = r"\d+(?=\s*feet)"
- result_8 = re.findall(pattern_8, text_8)
- print(*result_8)
- # 4
- print()
- # ################### Python Negative Lookahead ###########################
- print(" Negative Lookahead ")
- # Example:
- # X(?!Y)
- # The X(?!Y) matches X only if it is not followed by Y. It’s the \d+ not followed
- # by the literal string feet.
- text_9 = '1 Python is about 4 feet long'
- pattern_9 = '\d+(?!\s*feet)'
- matches = re.finditer(pattern_9, text_9)
- for match in matches:
- print(match.group())
- # 1
- print()
- # positive multiply
- print("positive multiply")
- text_10 = "Python3 Tutorial4B"
- pattern_10 = r'\b\w+(?=\d)(?=[A-Z])'
- result_10 = re.findall(pattern_10, text_10)
- print(result_10)
- # []
- print()
- text_11 = "Python3 Tutorial4B"
- pattern_11 = r'\b\w+(?=\d)(?=[A-Z]*)'
- result_11 = re.findall(pattern_11, text_11)
- print(result_11)
- # ['Python', 'Tutorial']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement