[英]Using a regex to check for special characters java
I want to check and see if a word contains a special character and remove it. 我想检查一个单词是否包含特殊字符并将其删除。 Lets say I have
String word = "hello-there"
, I want to loop through and check to see if the word doesn't contain a letter, then remove that special character and concatenate the word. 可以说我有
String word = "hello-there"
,我想遍历并检查该单词是否不包含字母,然后删除该特殊字符并连接该单词。 So I want to turn hello-there
into hellothere
using regex. 因此,我想使用正则表达式将
hello-there
转换为hellothere
。 I have tried this but I can't seem to figure out how to check individual characters of a string to a regex. 我已经尝试过了,但是我似乎无法弄清楚如何检查正则表达式中字符串的各个字符。
public static void main(String[] args){
String word = "hello-there";
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i).matches("^[a-zA-Z]+"))
But the last if statement doesn't work. 但是最后一个if语句不起作用。 Anybody know how to take care of this?
有人知道该怎么办吗?
You may use the following regex , that'll match any character, that is not a lower-case or upper-case letter. 您可以使用以下正则表达式 ,它将匹配任何字符,而不是小写或大写字母。
[^a-zA-Z]+
see regex demo 参见正则表达式演示
class RegEx {
public static void main(String[] args) {
String s = "hello-there";
String r = "[^a-zA-Z]+";
String o = s.replaceAll(r, "");
System.out.println(o); //-> hellothere
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.