For this code, all I want to do is split the original string into words by spaces and use regex to return the words that are not y, 4, !, or ?
However, I'm not sure why this isn't working:
public static void main (String[] args) {
System.out.println(makeWords("y are you not 4 !?"));
//should return string "are you not"
}
public static String makeWords (String str) {
String[] word = str.split(" ");
//make array of words
String result = "";
for (int i = 0; i < word.length; i++) {
if (word[i].matches("[^y4!?]")) {
String str = word[i];
result += str;
}
}
return result;
}
}
Your regex checks for words that are a single character (and that character must not match 'y', '4', '!', or '?'). None of your words meet that specification, so your result is empty string.
I think you need to change it like this:
public static String makeWords(String str) {
String[] word = str.split(" ");
// make array of words
String result = "";
for (int i = 0; i < word.length; i++) {
if (!word[i].matches("[y4!?]+")) {
String s = word[i];
result += s + " ";
}
}
return result;
}
This returns words that are one or more characters ( +
) and not consisting of combinations of y4!?
.
System.out.println(makeWords("y are you not 4 !?"));
Produces:
are you not
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.