Use regular expressions to remove rich text
Recently, when I was working, I encountered a need to remove rich text. To be honest, this function is still very simple, but the problems I encountered are not that simple...
Remove some rich text tags
We have a string with many rich text tags, such as:<size=60></size>
、<color=#F0F0F0></size>
etc. But we don't need to remove all the rich text tags, because I needKeep the colorRich text tags, onlyRemove font sizerich text tags, and the font size tags of rich text in strings also have various sizes, which is very troublesome.
You can also find various codes for removing rich texts online, but many of them are basically removed from all tags, and they rely on searching<
and>
If our string itself contains<
and>
, then the text in brackets will also be removed...
Later, the main course asked me to study itRegular expressions, one line of code solves it.
Code
private string RemoveRichTextSize(string sourceText) { sourceText = (sourceText, @"(<size=(\d+)>|</size>)", ""); return sourceText; }
It's actually very simple, just use it()
Just function, the most important thing is to understand the use of regular expressions.
(Original text, Matching rules, Replaced content);
The function requires inputting three parameters, and the following is a brief description
Because I need to remove the regular content, the replaced content is""
, so that the content is removed
In the matching rules@"(A|B)"
Represents a match A or B</size>
It's the end of rich text
The head of rich text<size=(\d+)>
It's just a difficult point\d
Represents matching a numeric character[0-9]
,(\d+)
Represents matching more than one number
By modifying the matching rules, you can also remove only the color attributes or italic attributes of rich text.
When writing this function, I referred to this boss's article, which also contains commonly used regular matching rules, which can be used.
C# regular expression collection
Summarize
This is the article about C# Unity using regular expressions to remove some rich texts. For more related C# Unity's regular expressions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!