[英]How to split a string between letters and digits (or between digits and letters)?
我正在嘗試找出一種在java中遵循以下模式的字符串拆分方法:
String a = "123abc345def";
結果應為:
x[0] = "123";
x[1] = "abc";
x[2] = "345";
x[3] = "def";
但是我對如何實現這一目標感到完全困惑。 有人可以幫我嗎? 我嘗試過在線搜索類似的問題,但是很難在搜索中正確地表達它的意思。
請注意:字母和數字的數量可能會有所不同(例如,可能有一個字符串,例如“ 1234a5bcdef”)
您可以嘗試分割(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)
,例如:
str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
它匹配數字和非數字之間的位置(以任何順序)。
(?<=\\D)(?=\\d)
-匹配非數字( \\D
)和數字( \\d
)之間的位置 (?<=\\d)(?=\\D)
-匹配數字和非數字之間的位置。 怎么樣:
private List<String> Parse(String str) {
List<String> output = new ArrayList<String>();
Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
while (match.find()) {
output.add(match.group());
}
return output;
}
您可以嘗試以下方法:
Pattern p = Pattern.compile("[a-z]+|\\d+");
Matcher m = p.matcher("123abc345def");
ArrayList<String> allMatches = new ArrayList<>();
while (m.find()) {
allMatches.add(m.group());
}
結果(allMatches)將是:
["123", "abc", "345", "def"]
使用兩種不同的模式: [0-9]*
和[a-zA-Z]*
並分別將其分割兩次。
如果您在不使用Java String
功能(例如split
, match
等)的情況下尋找解決方案,則以下內容應會有所幫助:
List<String> splitString(String string) {
List<String> list = new ArrayList<String>();
String token = "";
char curr;
for (int e = 0; e < string.length() + 1; e++) {
if (e == 0)
curr = string.charAt(0);
else {
curr = string.charAt(--e);
}
if (isNumber(curr)) {
while (e < string.length() && isNumber(string.charAt(e))) {
token += string.charAt(e++);
}
list.add(token);
token = "";
} else {
while (e < string.length() && !isNumber(string.charAt(e))) {
token += string.charAt(e++);
}
list.add(token);
token = "";
}
}
return list;
}
boolean isNumber(char c) {
return c >= '0' && c <= '9';
}
此解決方案將數字和“單詞”分開,其中“單詞”是不包含數字的字符串。 但是,如果您只希望包含英文字母的“單詞”,則可以根據需要添加更多條件(例如isNumber
方法調用)來輕松地對其進行修改(例如,您可能希望跳過包含非英文字母的單詞)。 還要注意, splitString
方法返回ArrayList
,以后可以將其轉換為String
數組。
我正在為關鍵任務代碼執行此類操作。 就像每一分之一秒一樣,因為我需要在不明顯的時間內處理180k條目。 因此,我跳過了正則表達式並完全拆分,並允許對每個元素進行內聯處理(盡管將它們添加到ArrayList<String>
會很好)。 如果您想做這件精確的事情,但需要將其速度提高20倍左右...
void parseGroups(String text) {
int last = 0;
int state = 0;
for (int i = 0, s = text.length(); i < s; i++) {
switch (text.charAt(i)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (state == 2) {
processElement(text.substring(last, i));
last = i;
}
state = 1;
break;
default:
if (state == 1) {
processElement(text.substring(last, i));
last = i;
}
state = 2;
break;
}
}
processElement(text.substring(last));
}
很久沒有使用Java了,所以只是一些偽代碼,應該可以幫助您入門(對我而言,比查找一切都快:))。
string a = "123abc345def";
string[] result;
while(a.Length > 0)
{
string part;
if((part = a.Match(/\d+/)).Length) // match digits
;
else if((part = a.Match(/\a+/)).Length) // match letters
;
else
break; // something invalid - neither digit nor letter
result.append(part);
a = a.SubStr(part.Length - 1); // remove the part we've found
}
這個"d+|D+"
不會代替繁瑣的工作: "(?<=\\\\D)(?=\\\\d)|(?<=\\\\d)(?=\\\\D)"
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.