Return all strings matching 'pattern' (a regex or callable) This is case-insensitive. If prune is true, return all items NOT matching the pattern. If field is specified, the match must occur in the specified whitespace-separated field. Examples::
(
self,
pattern: Union[str, Callable[[Any], re.Match[str] | None]],
prune: bool = False,
field: Optional[int] = None,
)
| 146 | p = paths = property(get_paths) |
| 147 | |
| 148 | def grep( |
| 149 | self, |
| 150 | pattern: Union[str, Callable[[Any], re.Match[str] | None]], |
| 151 | prune: bool = False, |
| 152 | field: Optional[int] = None, |
| 153 | ) -> Self: |
| 154 | """Return all strings matching 'pattern' (a regex or callable) |
| 155 | |
| 156 | This is case-insensitive. If prune is true, return all items |
| 157 | NOT matching the pattern. |
| 158 | |
| 159 | If field is specified, the match must occur in the specified |
| 160 | whitespace-separated field. |
| 161 | |
| 162 | Examples:: |
| 163 | |
| 164 | a.grep( lambda x: x.startswith('C') ) |
| 165 | a.grep('Cha.*log', prune=1) |
| 166 | a.grep('chm', field=-1) |
| 167 | """ |
| 168 | |
| 169 | def match_target(s: str) -> str: |
| 170 | if field is None: |
| 171 | return s |
| 172 | parts = s.split() |
| 173 | try: |
| 174 | tgt = parts[field] |
| 175 | return tgt |
| 176 | except IndexError: |
| 177 | return "" |
| 178 | |
| 179 | if isinstance(pattern, str): |
| 180 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) |
| 181 | else: |
| 182 | pred = pattern |
| 183 | if not prune: |
| 184 | return type(self)([el for el in self if pred(match_target(el))]) # type: ignore [no-untyped-call] |
| 185 | else: |
| 186 | return type(self)([el for el in self if not pred(match_target(el))]) # type: ignore [no-untyped-call] |
| 187 | |
| 188 | def fields(self, *fields: List[str]) -> List[List[str]]: |
| 189 | """Collect whitespace-separated fields from string list |