| OLD | NEW |
| (Empty) | |
| 1 # Copyright 2017 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 """Regular expression helpers.""" |
| 6 |
| 7 import re |
| 8 |
| 9 |
| 10 def _CreateIdentifierRegex(parts): |
| 11 assert parts |
| 12 if parts[0]: |
| 13 # Allow word boundary or a _ prefix. |
| 14 prefix_pattern = r'\b_?' |
| 15 else: |
| 16 # Allow word boundary, _, or a case transition. |
| 17 prefix_pattern = r'(?:\b|(?<=_)|(?<=[a-z])(?=[A-Z]))' |
| 18 parts = parts[1:] |
| 19 assert parts |
| 20 |
| 21 if parts[-1]: |
| 22 # Allow word boundary, trailing _, or single trailing digit. |
| 23 suffix_pattern = r'\d?_?\b' |
| 24 else: |
| 25 # Allow word boundary, _, or a case transition. |
| 26 suffix_pattern = r'(?:\b|(?=_|\d)|(?<=[a-z])(?=[A-Z]))' |
| 27 parts = parts[:-1] |
| 28 assert parts |
| 29 |
| 30 shouty_pattern = '_'.join(a.upper() for a in parts) |
| 31 snake_pattern = '_'.join(a.lower() for a in parts) |
| 32 camel_remainder = parts[0][1:] |
| 33 for token in parts[1:]: |
| 34 camel_remainder += token.title() |
| 35 first_letter = parts[0][0] |
| 36 prefixed_pattern = '[a-z]' + first_letter.upper() + camel_remainder |
| 37 camel_pattern = '[%s%s]%s' % (first_letter.lower(), first_letter.upper(), |
| 38 camel_remainder) |
| 39 middle_patterns = '|'.join( |
| 40 (shouty_pattern, snake_pattern, prefixed_pattern, camel_pattern)) |
| 41 return r'(?:%s(?:%s)%s)' % (prefix_pattern, middle_patterns, suffix_pattern) |
| 42 |
| 43 |
| 44 def ExpandRegexIdentifierPlaceholder(pattern): |
| 45 """Expands {{identifier}} within a given regular expression. |
| 46 |
| 47 Returns |pattern|, with the addition that {{some_name}} is expanded to match: |
| 48 SomeName, kSomeName, SOME_NAME, etc. |
| 49 |
| 50 To match part of a name, use {{_some_name_}}. This will additionally match: |
| 51 kPrefixSomeNameSuffix, PREFIX_SOME_NAME_SUFFIX, etc. |
| 52 |
| 53 Note: SymbolGroup.Where* methods call this function already, so there is |
| 54 generally no need to call it directly. |
| 55 """ |
| 56 return re.sub(r'\{\{(.*?)\}\}', |
| 57 lambda m: _CreateIdentifierRegex(m.group(1).split('_')), |
| 58 pattern) |
| OLD | NEW |