Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keep only alphabet characters

Tags:

java

string

regex

What method should I follow in java to produce

"WordWord" 

from

"Word#$#$% Word 1234" 
like image 797
ssrp Avatar asked Mar 26 '12 12:03

ssrp


People also ask

What does alphabetic characters only mean?

Noun. 1. alphabetic character - the conventional characters of the alphabet used to represent speech; "his grandmother taught him his letters" letter of the alphabet, letter. spelling - forming words with letters according to the principles underlying accepted usage.

How do you keep letters only in a string?

You can use the regular expression 'r[^a-zA-Z]' to match with non-alphabet characters in the string and replace them with an empty string using the re. sub() function. The resulting string will contain only letters.

How do I select only the alphabet in Word?

[A-Za-z] will match all the alphabets (both lowercase and uppercase). ^ and $ will make sure that nothing but these alphabets will be matched.

How do I filter only the alphabet in Python?

The method string. isalpha() checks whether string consists of alphabetic characters only. You can use it to check if any modification is needed.


1 Answers

You can use String.replaceAll(regex, replacement) with the regex [^A-Za-z]+ like this:

String newstr = "Word#$#$% Word 1234".replaceAll("[^A-Za-z]+", ""); // newstr will become WordWord 

Edit: Although OP hasn't mentioned anything about unicode characters but since @Joey has made a comment and if at all there a requirement to keep unicode characters then \\P{L}+ regex should be used like this:

String newstr = "Word#$#$% Word λ1234ä, ñ, ж".replaceAll("\\P{L}+", ""); // newstr will become WordWordλäñж 
like image 113
anubhava Avatar answered Sep 23 '22 06:09

anubhava