Advertisement
Guest User

Untitled

a guest
Nov 12th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.49 KB | None | 0 0
  1. import re
  2. with open('file.txt', 'r') as f:
  3.     text = f.read()
  4. pattern = r"mypattern"
  5.  
  6. # Get the first match
  7. match = re.search(pattern, text)
  8.  
  9. # Get all matches
  10. matches = re.findall(pattern, text)
  11.  
  12. # Replace any matches with "replacement"
  13. text_replaced = re.sub(pattern, "replacement", text)
  14.  
  15. # Print the match
  16. print(match)
  17.  
  18. # Print any captured groups
  19. print(match.groups())
  20.  
  21. # Write the replacement text back to the file
  22. with open('file.txt', 'w') as f:
  23.     f.write(text_replaced)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement