rich icon indicating copy to clipboard operation
rich copied to clipboard

How to remove formatting styles from string?

Open loot-midget opened this issue 2 months ago • 3 comments

Hi,

I would like to search custom substring in items' text but now tags/color names are matching too.

Is there a way to cleanup tags/styles from passed string?

Thank you.

Update: the goal is filtering menu items which could be styled: https://github.com/petereon/beaupy/issues/201

loot-midget avatar Sep 23 '26 20:09 loot-midget

Use Text.from_markup(value).plain to get the displayed text without the markup. Keep the original string for the menu, and use the plain text only as the search key.

For the filter_options() in your linked Beaupy example:

from rich.text import Text

def filter_options(*, options: list[str], substring: str) -> list[str]:
    if not substring:
        return list(options)
    needle = substring.lower()
    return [
        item
        for item in options
        if needle in Text.from_markup(item).plain.lower()
    ]

For example, [bold red]Apple[/bold red] is searched as Apple: red no longer matches, while app does. The returned item still contains its original styling.

I checked this search function with Rich 15.0.0, including style-name exclusion, case-insensitive visible text, link text versus its hidden URL, empty filters, emoji expansion, and escaped literal brackets. This checks the filtering step, not a complete interactive Beaupy session.

API reference

AI assistance disclosure: prepared and tested for Youngseok Oh using OpenAI Codex.

YS-OH-CORE avatar Sep 26 '26 04:09 YS-OH-CORE

It works! Thank you!

loot-midget avatar Sep 26 '26 11:09 loot-midget

I hope I helped!

Consider sponsoring my work on Rich. I give tech support for free, in addition to maintaining Rich and Textual.

If you like using Rich, you might also enjoy Textual.

Will McGugan

github-actions[bot] avatar Sep 26 '26 11:09 github-actions[bot]