[英]How to get an array of character (A-z, no numbers) from a given string?
我需要一個 java 正則表達式來回答我的問題。
這是我的代碼:
char[] array = s.split("regex");
首先用空格替換非字母字符,然后將 String 轉換為 char 數組:
char[] onlyLetters = "regex".replaceAll("[^A-Za-z]+", "").toCharArray();
正如您在問題下方的評論中所說,您真正想要的是獲取給定字符串的單個字符,這可以通過String
類中的toCharArray()
方法實現。
String s = "ABCDEfghi1234";
char[] chars = s.toCharArray();
如果您還需要將結果字符限制為一組定義的字符,則必須首先從字符串中刪除所有其他字符,這可以通過簡單的正則表達式替換來完成。
String s = "ABCDEfghi1234_.,-DSsf";
s = s.replaceAll("[^A-Za-z]", "");
char[] chars = s.toCharArray();
您使用的split
方法通常用於在定義的位置拆分字符串,例如,如果您想拆分一個句子,用空格分隔。
String sentence = "The quick brown fox jumps over the lazy dog";
String[] words = sentence.split("\\s");
// words now contains the extracted words of the sentence
// words[0] == "The"
// words[1] == "quick"
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.