Removing all fraction symbols like “¼” and “½” from a string

五迷三道 提交于 2019-11-27 13:23:26

问题


I need to modify strings similar to "¼ cups of sugar" to "cups of sugar", meaning replacing all fraction symbols with "".

I have referred to this post and managed to remove ¼ using this line:

itemName = itemName.replaceAll("\u00BC", "");

but how do I replace every possible fraction symbol out there?


回答1:


Fraction symbols like ¼ and ½ belong to Unicode Category Number, Other [No]. If you are ok with eliminating all 676 characters in that group, you can use the following regular expression:

itemName = itemName.replaceAll("\\p{No}+", "");

If not, you can always list them explicitly:

// As characters (requires UTF-8 source file encoding)
itemName = itemName.replaceAll("[¼½¾⅐⅑⅒⅓⅔⅕⅖⅗⅘⅙⅚⅛⅜⅝⅞↉]+", "");

// As ranges using unicode escapes
itemName = itemName.replaceAll("[\u00BC-\u00BE\u2150-\u215E\u2189]+", "");



回答2:


You can use below regex to replace all fraction with empty string.

str = str.replaceAll("(([\\xbc-\\xbe])?)", "")


来源:https://stackoverflow.com/questions/43359325/removing-all-fraction-symbols-like-%c2%bc-and-%c2%bd-from-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!