簡體   English   中英

使用正則表達式檢查特殊字符Java

[英]Using a regex to check for special characters java

我想檢查一個單詞是否包含特殊字符並將其刪除。 可以說我有String word = "hello-there" ,我想遍歷並檢查該單詞是否不包含字母,然后刪除該特殊字符並連接該單詞。 因此,我想使用正則表達式將hello-there轉換為hellothere 我已經嘗試過了,但是我似乎無法弄清楚如何檢查正則表達式中字符串的各個字符。

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]+"))

但是最后一個if語句不起作用。 有人知道該怎么辦嗎?

您可以使用以下正則表達式 ,它將匹配任何字符,而不是小寫或大寫字母。

[^a-zA-Z]+ 

參見正則表達式演示

Java演示

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM