Remove all fraction characters, such as ¼ and ½ from a string

I need to change lines similar to "¼ cups of sugar" to "cups of sugar", which means replacing all fraction characters with "".

I mentioned this post and was able to remove ¼ with this line:

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

but how can I replace all possible fraction characters?

+57
java replaceall
Apr 12 '17 at 2:41 on
source share
2 answers

Fractional characters such as ¼ and ½ are categorized as Unicode Number, Other [No] . If you are fine with eliminating all 676 characters in this group, you can use the following regular expression:

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

If not, you can always specify 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]+", ""); 
+90
Apr 12 '17 at 2:49 on
source share

You can use the regex below to replace the entire fraction with an empty string.

 str = str.replaceAll("(([\\xbc-\\xbe])?)", "") 
+1
Apr 12 '17 at 2:55 on
source share



All Articles