我目前在java中有以下字符串:
"Blah, blah, blah,~Part One, Part Two~,blah blah"
我需要删除~
字符之间的逗号,以便读取。
"Blah, blah, blah,~Part One Part Two~,blah blah"
有人可以帮帮我吗?
非常感谢,
答案 0 :(得分:5)
String[] tests = {
"a,b,c,d,e,f",
"a,b,~c~,d,e",
"~a,b,c,d,e~",
"a,b,c,~d,e,f~,g,h,i,~j,k,l,~m,n,o~,q,r,~s,t,u",
};
for (String test : tests) {
System.out.println(
test.replaceAll(
"(^[^~]*~)|([^~]*$)|([^,~]*),|([^,~]*~[^~]*~)",
"$1$2$3$4"
)
);
}
以上版画:
a,b,c,d,e,f
a,b,~c~,d,e
~abcde~
a,b,c,~def~,g,h,i,~jkl~m,n,o~qr~s,t,u
有4个案例:
~
,所以下次我们会“在里面”(^[^~]*~)
~
~
,我们就会“在外面”([^~]*$)
~
之前找到下一个逗号(所以我们仍在“内部”)
([^,~]*),
(不要捕捉逗号!)~
而不是逗号,那就出去吧,然后再回到下一个~
([^,~]*~[^~]*~)
在所有情况下,我们确保捕获足够的数据来重建字符串。
答案 1 :(得分:0)
我没有测试过这个,但我会做类似的事情:
string sample = "Blah, blah, blah,~Part One, Part Two~,blah blah";
Regex r = new Regex("(.+)\\~(.+),(.+)\\~(.+)","${1}~${2}${3}~${4}");
r.replaceAll(sample );
我引用了Regular Expressions in Java。在这里,。+匹配一个或多个任何字符。可以找到更多此类模式here。
答案 2 :(得分:0)
String text = "Blah, blah, blah,~Part One, Part Two~,blah blah,~Part One, Part Two~,blah blah";
Pattern pattern = Pattern.compile("~[^~]+~");
Matcher matcher =pattern.matcher(text);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, matcher.group(0).replaceAll(",", ""));
}
matcher.appendTail(sb);
text = sb.toString();
答案 3 :(得分:0)
这是一种可以胜任的方法:
public String deleteCharacterBetween(String deleteFrom, String betweenChar, String charToRemove) {
int nextIndex = 0, index = 0;
while (true) {
index = deleteFrom.indexOf(betweenChar, nextIndex);
nextIndex= deleteFrom.indexOf(betweenChar, index + 1);
if (nextIndex < 0 || index < 0)
return deleteFrom;
String before = deleteFrom.substring(0, index);
String toEdit = deleteFrom.substring(index, nextIndex);
String after = deleteFrom.substring(nextIndex);
toEdit = toEdit.replace(charToRemove, "");
deleteFrom = before + toEdit + after;
}
}
您可以这样称呼它:
String a = "Blah, blah, blah,~Part One, Part Two~,blah blahBlah, blah, blah,~Part One, Part Two~,blah blah";
System.out.println(deleteCharacterBetween(a, "~", ","));