misc_utils.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright 2014 Google Inc.
  2. #
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Miscellaneous utilities."""
  6. import re
  7. class ReSearch(object):
  8. """A collection of static methods for regexing things."""
  9. @staticmethod
  10. def search_within_stream(input_stream, pattern, default=None):
  11. """Search for regular expression in a file-like object.
  12. Opens a file for reading and searches line by line for a match to
  13. the regex and returns the parenthesized group named return for the
  14. first match. Does not search across newlines.
  15. For example:
  16. pattern = '^root(:[^:]*){4}:(?P<return>[^:]*)'
  17. with open('/etc/passwd', 'r') as stream:
  18. return search_within_file(stream, pattern)
  19. should return root's home directory (/root on my system).
  20. Args:
  21. input_stream: file-like object to be read
  22. pattern: (string) to be passed to re.compile
  23. default: what to return if no match
  24. Returns:
  25. A string or whatever default is
  26. """
  27. pattern_object = re.compile(pattern)
  28. for line in input_stream:
  29. match = pattern_object.search(line)
  30. if match:
  31. return match.group('return')
  32. return default
  33. @staticmethod
  34. def search_within_string(input_string, pattern, default=None):
  35. """Search for regular expression in a string.
  36. Args:
  37. input_string: (string) to be searched
  38. pattern: (string) to be passed to re.compile
  39. default: what to return if no match
  40. Returns:
  41. A string or whatever default is
  42. """
  43. match = re.search(pattern, input_string)
  44. return match.group('return') if match else default