Perform regex match in rich text lines. Produces a new RichTextLines object with font_attr_segs containing highlighted regex matches. Example use cases include: 1) search for specific items in a large list of items, and 2) search for specific numerical values in a large tensor. Args:
(orig_screen_output, regex, font_attr)
| 379 | |
| 380 | |
| 381 | def regex_find(orig_screen_output, regex, font_attr): |
| 382 | """Perform regex match in rich text lines. |
| 383 | |
| 384 | Produces a new RichTextLines object with font_attr_segs containing highlighted |
| 385 | regex matches. |
| 386 | |
| 387 | Example use cases include: |
| 388 | 1) search for specific items in a large list of items, and |
| 389 | 2) search for specific numerical values in a large tensor. |
| 390 | |
| 391 | Args: |
| 392 | orig_screen_output: The original RichTextLines, in which the regex find |
| 393 | is to be performed. |
| 394 | regex: The regex used for matching. |
| 395 | font_attr: Font attribute used for highlighting the found result. |
| 396 | |
| 397 | Returns: |
| 398 | A modified copy of orig_screen_output. |
| 399 | |
| 400 | Raises: |
| 401 | ValueError: If input str regex is not a valid regular expression. |
| 402 | """ |
| 403 | new_screen_output = RichTextLines( |
| 404 | orig_screen_output.lines, |
| 405 | font_attr_segs=copy.deepcopy(orig_screen_output.font_attr_segs), |
| 406 | annotations=orig_screen_output.annotations) |
| 407 | |
| 408 | try: |
| 409 | re_prog = re.compile(regex) |
| 410 | except sre_constants.error: |
| 411 | raise ValueError("Invalid regular expression: \"%s\"" % regex) |
| 412 | |
| 413 | regex_match_lines = [] |
| 414 | for i, line in enumerate(new_screen_output.lines): |
| 415 | find_it = re_prog.finditer(line) |
| 416 | |
| 417 | match_segs = [] |
| 418 | for match in find_it: |
| 419 | match_segs.append((match.start(), match.end(), font_attr)) |
| 420 | |
| 421 | if match_segs: |
| 422 | if i not in new_screen_output.font_attr_segs: |
| 423 | new_screen_output.font_attr_segs[i] = match_segs |
| 424 | else: |
| 425 | new_screen_output.font_attr_segs[i].extend(match_segs) |
| 426 | new_screen_output.font_attr_segs[i] = sorted( |
| 427 | new_screen_output.font_attr_segs[i], key=lambda x: x[0]) |
| 428 | regex_match_lines.append(i) |
| 429 | |
| 430 | new_screen_output.annotations[REGEX_MATCH_LINES_KEY] = regex_match_lines |
| 431 | return new_screen_output |
| 432 | |
| 433 | |
| 434 | def wrap_rich_text_lines(inp, cols): |