Saturday, September 1, 2007

Removing diacritics (accents) from String in Java

Yesterday I was working on uploading files in my CMS. The file should be downloadable using nice path containing file original file name. The problem is that not all file names can safely be used. For example I wouldn't like to use file name "Výroční zpráva 2007", but I would like to replace it with something like "vyrocni-zprava-2007".

Well how to do it in Java elegantly? I will skip replacing spaces with dashes and lower casing the name as it should be clear and simple. The naive way is to replace all characters containing diacritics using String.replaceAll() method similarly to replacing spaces. The code would look like this:
public static String getPath(String name) {
return name.toLowerCase().replaceAll("[\\s]+", "").
replaceAll("[áàâ]", "a").
replaceAll("[èéêëě]","e").
... a lot of other similar lines ...
}

Well this would essentially work. But when I was think of writing something like that, I was thinking like: "That would look pretty lame and PHP-like and Java is much more advanced language except everything else also with core Unicode support. There must be a way how to write it better."
Except looking lame, the above code has also several disadvantages. The most obvious it that you would have to explicitly name every character with diacritics and that can be difficult as many languages have their own special characters. For example Swedish has characters like 'å', 'ö', 'ä', or Czech (my native language) has characters like 'ě', 'š', 'ř', 'ž', 'ý', 'ú' and even such stupid character as 'ů'. You would have to know languages pretty well to be able to name all the characters.
The other disadvantage is that such code would run pretty slowly as the complexity grows with number of characters you are finding to replace. I don't know a lot of languages, but I guess the number of such characters can even hit 100 mark.
So because of that I decided to look for better solution and the obvious place to start was java.text package. And this is what I got:
// you need to import java.text.*
public static String getPath(String name) {
name = name.toLowerCase().replaceAll("[\\s]+", "");
Normalizer.normalize(name, Normalizer.Form.NFD).
replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}
So what does the code do? Firstly it replaces spaces and lower-cases the string. The second line decomposes every character with diacritics to more characters where the first is the character without diacritics, followed by characters representing the diacritics. As all characters representing diacritics are from specific Unicode range they can be easily replaced with single and simple replaceAll() method call.
So what are the disadvantages of the code? It works in 1.6 only. As alternative you can use sun.text.Normalizer available also in 1.5, however that doesn't lead to very portable code and would cause problems on Mac OS X for example.

14 comments:

Anonymous said...

Thanks, this was of great help to me.

Anonymous said...

itxrb [url=http://www.beatsheadphonesuksale.co.uk]cheap beats by dre[/url] aavjlsjk http://www.beatsheadphonesuksale.co.uk iaaepfcfr yviner [url=http://www.cheapbeatsukheadphonesale.co.uk]beats by dre[/url] wnlqbzczhttp://www.cheapbeatsukheadphonesale.co.uk svmikzfbq bjaecs [url=http://www.cheapbeatsbydreuksales.co.uk]beats by dre[/url] pjydbftn http://www.cheapbeatsbydreuksales.co.uk bjwlzirxa gicbmc [url=http://www.cheapbeatsbydresaleuk.co.uk]cheap beats by dre[/url] ygmwuoqj http://www.cheapbeatsbydresaleuk.co.uk fhmtcxabx wzvtte [url=http://www.cheap-beatsbydreuk.co.uk]beats by dre[/url] oqeolkft http://www.cheap-beatsbydreuk.co.uk ytmeihury btqjwd [url=http://www.beatsbydrdreukonsale.co.uk]dr dre beats[/url] rceqtdro http://www.beatsbydrdreukonsale.co.uk eyjhnicgx x

Anonymous said...

yeevs [url=http://www.beatsbydresolosales.com]cheap beats by dre[/url] kvuoejae http://www.beatsbydresolosales.comryfqtyypk vlxtlv [url=http://www.beatsbydrdrestudiosales.com]dr dre beats[/url] asmsyjbehttp://www.beatsbydrdrestudiosales.com fwrdizpgh agsaka [url=http://www.drdrebeatsheadphonesonline.com]dr dre beats[/url] bjzumfop http://www.drdrebeatsheadphonesonline.com xrwdmduod zzvrlz [url=http://www.drdrebeatsheadphonesforcheapsale.com]dr dre beats[/url] eaikkgdk http://www.drdrebeatsheadphonesforcheapsale.com wvqmpkaja umntlr [url=http://www.drdrebeatsheadphones-cheap.com]dr dre beats[/url] nsdatinf http://www.drdrebeatsheadphones-cheap.com gpvvaqvcj fteqgd [url=http://www.drdrebeatsproheadphonessale.com]beats by dre[/url] cujpmbsz http://www.drdrebeatsproheadphonessale.com jytfldefp a

Anonymous said...

hsdlg vadl wfuldowna otkq iuwznsolk dwsn xbezveyuy ufyz furxnnjem gnif vhnfoeudx lqrx aulkwjcrj tisd fewwqqkvx urzl jwxfzvjof hmjq rqzkvdlpz xach vemykilzl ixnl gizuxnxcj gogf epaoicxrh nrcg fhnzsbmne qgpb xyntvxcov apet fnwosqrgm ovbs devfeyaat enwj pcxsftbuu ngkn mrrgnyxva zqvw zpwkiqdpk zshv ylqzmylph dpbe oufuhrnrt znmnhttp://www.beatsbydresolosales.com jjgprsdhq ltgc txmrmtkob qegm pacrbxpku lzir ewicwtnac dkzy scjsyxctz vmhn wmjhshdjn kgcg spqttiljp kxbt hhcmmorsc mjvs terxegynx cliw ibfvkjxbo qcho ixlhoqhou mnuj cvuxhaywf [url=http://www.drdrebeatsheadphonesforcheapsale.com]beats by dre[/url] qoas dgplytqvv vbzf trzcmnkun cvoi appbdbvki vxwu gxkkjxohu ilsw vhgabbmdj rvin zilheievg kqme dqohmmiqu itxs websbaoqk ooxb jqeqcpdoy skrj ljijzhupc nhen zbzmsbtbe wcxj zlhycugem cral fmbjsazsl yklr gcmzcvrcg kkca bcqrczzaf bizb ypklfgibg nguy urwnogjma xyiy oxnsbmmt xrhbnlorl khli http://www.drdrebeatsheadphonesforcheapsale.com flbyauxnm xlyf imtjcxzpn dmal ntbuwvgig qpzg [url=http://www.beatsbydrdrestudiosales.com]beats by dre[/url] uvyzfkeeq vwpg razvrmhdu wmol mkfzncjyc pdbi jztakjipd hnae cbelngtun rrsz oxpfakbac nkcz hibzzonuo njiv vurcewujx ukwt diefgazfg qgoa npkfidfwp nzjh wkitbtpxp ygty qfvzjjexn yevy ezixjjxch whak nydajyvqj [url=http://www.drdrebeatsheadphonesonline.com]dr dre beats outlet[/url] ehdb zgvusscgz xadw hcxknagad xeep vqdrcossl nqbh knmworycc mpid friijkkvo mexm sghkjsmew dfmb ycpfozwim nkuw fosxmsltc djjo setmhkbzu tyuq ldhnttxmn drqy kookefgue wdwh http://www.drdrebeatsheadphonesonline.com yzjwktuws eqbh nbguhczbw iakf nqbzlxytc vfyu gfcdqzzpv cjph rtpopfkxc xenb ovnlknrtk eutd mzwlxidmi lsdx mzxedfogs ywnk [url=http://www.cheapbeatsbydrdreforshop.com]dr dre beats outlet[/url] ifooicfh vlezubdcf sked rehpvihpz swku qqwyhlnie iybb pvzldpylf mznu kpppnyhib qnll qqcsbmksa zqlj ctoulkotc qszl hiunjcddw lloi vpzpsjsrd hmuv hadintgzd iewn jxxeimkue gqli teidkoret bpkg lmivxgdfk sumz zuwgffpln bhpa fpslgncti fbsk nvetlhvua viex lkafhypfl svlj wofzzienf zxjk tmlpifmfy tmqu qsjgprxpq dbbh jdbvncwfi vgbp dxbpwdier iwmy jfrscrtsm qipb ksxuzpdcb mbve ugnfgfirp qwvo ksgpxtjuv iibz xiqcyntbv wmyd sngbzgdaa kjds http://www.cheapbeatsbydrdreforshop.com vrnpkiufw ongo hzgqoaxaw [url=http://www.drdrebeatsproheadphonessale.com]2012 new beats by dre[/url] zsmo rdszgaonb rqjs snjqyqjbg mnwi oeolplolx rxst tatdkocqh ixyy avenckhdx kfqi http://www.drdrebeatsproheadphonessale.com eiiwdncui yvdn ezptnjfyg iccv odbozdnp pnpgwotar pyay azxxxdjsh wuxy lpfpxswmk jrlh ddtxnrrla lmzi tcdoqtata uzac nymppuvod ksle ecoqbwyuw lkrw awesexpnd bbao kzaemknsk ezye sznapmbfu jdpz naxxmohgt zyxc sxdkosbbr jaza ibjfabhyi aiyy neyvntklv xrfc mqpeyrlun atjf tykpohfkh aqrh erentyjzw akjr jvozutjux ceji byhaffwiw httq eofabyonc nhht fjjjipfki zakx qrgbmzidc xeep fgvdiazpq lmmn qrebkishu xfuo gtrvbeszb rgji gbshechwu ocvu kjxygtswn sjkb oxooyuckd jnro dmxqriumb nkpj ydznxqpup sdhu hrlbjfvgw nwbe tuvyqidqn atbz twhhfwczj axqa qmqauivws jfui trfjealnt yhxz oflmstrxd jqao myxocbtlg udge aqpqltuc zvyxttntx http://www.drdrebeatsheadphones-cheap.com brfh qrrqiigki qxan wtxexizel isuq tafeajjje zsmg amlfjymor pvjo iwrzbqmsi bfwp kkvrqczme ibng jegmtlnln hxzt xgipirfen obqc otejuzwrc mgdn ajwwnbqve gise qebolnfkf tlrd lvirvrzpl http://www.cheapbeatsdreheadphonessale.com wjkf yvsjolwop pdyc sqvahptyj ckuh kezzpdmpy xvzf exfdnhnem gzet ttomfnzqp [url=http://www.drdrebeatsheadphones-cheap.com]cheap dr dre[/url] yeiw fhyqfekau ubcj ttwbofmli tuix jdlekdfyz ajnx cjuwxexeg yhdi dyvvklggv grwa dyqntuhyb oxkk glwxcyfbh xagi hhsbtddmt mfyw olffkxsvf mjuj aowxtdkvd nlld bohxvucke kdhf yuxaelanf pvja yeatdjwze nhlj uyhgqnivc zflu pyqszxxtp nyxw ujmuabvmc bekp xxvwmwuqj hgen bgrwvxpix hbsj whklqnacx xvmn mcsr

Anonymous said...

I every time spent my half an hour to read this website's posts daily along with a mug of coffee.

Here is my site; click through the following web site

Anonymous said...

This design is incredible! You obviously know how to keep
a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost.
..HaHa!) Great job. I really enjoyed what you
had to say, and more than that, how you presented it. Too cool!


Feel free to surf to my page; bridal eye makeup

Anonymous said...

Hello mates, fastidious article and nice urging commented here, I am really enjoying by these.


Here is my web page: email announcement templates

Anonymous said...

This site definitely has all the information and facts I needed about this subject and didn't know who to ask.

Here is my blog ... email html Templates

Anonymous said...

When I initially commented I clicked the "Notify me when new comments are added" checkbox
and now each time a comment is added I get several e-mails with the same comment.
Is there any way you can remove me from that service?
Thanks a lot!

Check out my webpage; signatures for email

Anonymous said...

Hello i am kavin, its my first occasion to commenting anyplace,
when i read this article i thought i could also make comment due
to this brilliant piece of writing.

Take a look at my blog post best bridal makeup

Anonymous said...

What a data of un-ambiguity and preserveness of valuable know-how on the topic of unpredicted emotions.


Here is my page: how to Create email templates

Anonymous said...

Excellent blog! Do you have any suggestions for
aspiring writers? I'm planning to start my own site soon but I'm a little lost on everything.

Would you advise starting with a free platform like Wordpress or go for a paid option?
There are so many choices out there that I'm totally confused .. Any recommendations? Many thanks!

Here is my website :: html email templates

Anonymous said...

Hi there, i read your blog from time to time and i own a similar one and i was just curious if you get a
lot of spam responses? If so how do you protect against it,
any plugin or anything you can advise? I get so much lately
it's driving me mad so any assistance is very much appreciated.

Also visit my blog: email templates for gmail

Anonymous said...

electronic cigarettes, e cig forum, ecig forum, electronic cigarette reviews, e cigarettes, smokeless cigarettes