'extract word from string that have combination of letter and number in java?
this is my first question and sorry for my bad English
I want to extract only word from String that have combination of letter and number and store it in array
I try this code, but I don't get what I want
String temp = "74 4F 4C 4F 49 65 brown fox jump over the fence";
String [] word = temp.split("\\W");
this is the result that I want (only word and no empty array)
brown
fox
jump
over
the
fence
Please help, Thank you !
Solution 1:[1]
You can use:
String temp = "74 4F 4C 4F 49 65 brown fox jump over the fence";
List<String> arr = new ArrayList<String>();
Pattern p = Pattern.compile("(?i)(?:^|\\s+)([a-z]+)");
Matcher m = p.matcher(temp);
while (m.find())
arr.add(m.group(1));
// convert to String[]
String[] word = arr.toArray(new String[0]);
System.out.println( Arrays.toString(word) );
OUTPUT:
[brown, fox, jump, over, the, fence]
Solution 2:[2]
Based on @anubhava's answer, you could do something like
String temp = "74 4F 4C 4F 49 65 brown fox jump over the fence";
Pattern pattern = Pattern.compile("\\b[A-Za-z]+\\b");
Matcher matcher = pattern.matcher(temp);
while (matcher.find()) {
System.out.println("Matched " + matcher.group());
}
Solution 3:[3]
Works for:
There are already some answers here but this is the one I'd preferred to do that. Try this code:
List<String> wordsOnlyList = new ArrayList<>(); // This list contains all the words without numbers or special chars
String sentence = "I bought a A7A for $36,000"; // This is a sample sentence to test the result
String[] words = sentence.split(" "); // split into each word
for(String word : words){
if (!(Pattern.compile("[^a-z ]", Pattern.CASE_INSENSITIVE).matcher(word).find())) { //checking if it has only alphabets
// it has only alphabets
wordsOnlyList.add(word); // add the word to the list
}
}
System.out.println(wordsOnlyList.toString()); // display in console
Result:
[I, bought, a, for]
You can also test the code from here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Sambhav. K |