我正在编写一个程序来获取字符串的不同部分,例如“10万亿8370亿4500万56739”。我问了这个问题here 。 但有时我的字符串会变得像“10万亿8370亿4500万56739”。 我想删除“56 739”中 6 和 7 之间的空格。
我知道删除空格,但不知道如何指定哪些字符之间是要删除的空格
这是我的代码
String input = "10 trillion 837 billion 45 million 56 739";
String pattern = "\\s\\d"; // this will match space and number thus will give you start of each number.
ArrayList<Integer> inds = new ArrayList<Integer>();
ArrayList<String> strs = new ArrayList<String>();
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
inds.add(m.start()); //start will return starting index.
}
//iterate over start indexes and each entry in inds array list will be the end index of substring.
//start index will be 0 and for subsequent iterations it will be end index + 1th position.
int indx = 0;
for(int i=0; i <= inds.size(); i++) {
if(i < inds.size()) {
strs.add(input.substring(indx, inds.get(i)));
indx = inds.get(i)+1;
} else {
strs.add(input.substring(indx, input.length()));
}
}
for(int i =0; i < strs.size(); i++) {
Toast.makeText(getApplicationContext(),strs.get(i)+"",Toast.LENGTH_LONG).show();
}
我尝试添加像这样的replaceAll语句input = input.replaceAll("\\d\\s\\d","\\d\\d");
但它没有'工作吧
最佳答案
我发现(或假设)的是,您正在尝试删除 string
中数字之间的空格。所以,
您可以使用这个regex
替换您的 space
数字之间:
(?<=\\d)\\s+(?=\\d|\\-)
像:
input = input.replaceAll("(?<=\\d)\\s+(?=\\d|\\-)", "");
(?<=\d)
是一个积极的lookbehind,它检查前一个符号是否是数字,而不实际匹配它。
(?=\d)
是一个积极的前瞻,同样的事情 - 检查后面的符号是否是数字,而不实际匹配它。
您可以在此处测试正则表达式: https://regex101.com/r/pdEoKO/1/
关于java - 如何替换两个数字之间的每个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56539117/