Use the regex, [^\w-]
which means NOT(a word character or -
).
public class Main {
public static void main(String[] args) {
// Test
String word = "Hello :) Hi, How are you doing? The Co-operative bank is open 2day!";
word = word.replaceAll("[^\\w-]", "").toLowerCase();
System.out.println(word);
}
}
Output:
hellohihowareyoudoingtheco-operativebankisopen2day
Note that a word character (i.e. \w
) includes A-Za-z0-9_
. If you want your regex to restrict only up to alphabets and hyphen, you should use [^A-Za-z\-]
public class Main {
public static void main(String[] args) {
// Test
String word = "Hello :) Hi, How are you doing? The Co-operative bank is open 2day!";
word = word.replaceAll("[^A-Za-z\\-]", "").toLowerCase();
System.out.println(word);
}
}
Output:
hellohihowareyoudoingtheco-operativebankisopenday