How to remove formatting styles from string?
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
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.
AI assistance disclosure: prepared and tested for Youngseok Oh using OpenAI Codex.
It works! Thank you!
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