3 回答

TA貢獻2021條經驗 獲得超8個贊
匹配這些子字符串更容易:
String content = "aba(2)bb(52)gc(4)d(2)fe(14)f(6)g(8)h(4)5(6)";
Pattern pattern = Pattern.compile("[a-g](?:\\(\\d+\\))?");
List<String> res = new ArrayList<>();
Matcher matcher = pattern.matcher(content);
while (matcher.find()){
res.add(matcher.group(0));
}
System.out.println(res);
輸出:
[a, b, a(2), b, b(52), g, c(4), d(2), f, e(14), f(6), g(8)]
圖案詳情
[a-g]
- 一封來自a
于的信g
(?:\(\d+\))?
- 一個可選的非捕獲組匹配 1 或 0 次出現\(
- 一個(
字符\d+
- 1+ 位數字\)
- 一個)
字符。

TA貢獻1810條經驗 獲得超4個贊
如果你只想使用 split 方法,這里有一個你也可以遵循的方法,
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
String content = "aba(2)bb(52)gc(4)d(2)fe(14)f(6)g(8)h(4)5(6)";
String[] a = content.replaceAll("[a-g](\\([0-9]*\\))?|[a-g]", "$0:").split(":");
// $0 is the string which matched the regex
System.out.println(Arrays.toString(a));
}
}
正則表達式:[a-g](\\([0-9]*\\))?|[a-g]匹配你想匹配的字符串(即a、b、a(5)等)
使用這個正則表達式,我首先用它們的附加版本(附加:)替換這些字符串。后來,我使用 split 方法拆分字符串。
上面代碼的輸出是,
[a, b, a(2), b, b(52), g, c(4), d(2), f, e(14), f(6), g(8), h(4)5(6)]
注意:此方法僅適用于已知不存在于輸入字符串中的分隔符。例如,我選擇了一個冒號,因為我認為它不會成為輸入字符串的一部分。

TA貢獻2037條經驗 獲得超6個贊
您可以嘗試以下正則表達式: [a-g](\(.*?\))?
[a-g]: 需要從 a 到 g 的字母
(\(.*?\))?:(和之間的任何字符),盡可能少地匹配
您可以在此處查看預期的輸出。
這個答案基于Pattern一個例子:
String input = "aba(2)bb(52)gc(4)d(2)fe(14)f(6)g(8)h(4)5(6)";
Pattern pattern = Pattern.compile("[a-g](?:\\(\\d+\\))?");
Matcher matcher = pattern.matcher(input);
List<String> tokens = new ArrayList<>();
while (matcher.find()) {
tokens.add(matcher.group());
}
tokens.forEach(System.out::println);
結果輸出:
a
b
a(2)
b
b(52)
g
c(4)
d(2)
f
e(14)
f(6)
g(8)
編輯:使用[a-g](?:\((.*?)\))?您還可以輕松提取括號的內部值:
while (matcher.find()) {
tokens.add(matcher.group());
tokens.add(matcher.group(1)); // the inner value or null if no () are present
}
添加回答
舉報