I currently have the following string in java:
"Blah, blah, blah,~Part One, Part Two~,blah blah"
I need to remove the comma between the ~
character so it reads.
"Blah, blah, blah,~Part One Part Two~,blah blah"
Can anyone help me out please?
Many thanks,
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"
)
);
}
The above prints:
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
There are 4 cases:
~
, so next time we'll be "inside" (^[^~]*~)
~
till the end of the string
~
, we'll be "outside" ([^~]*$)
~
(so we're still "inside")
([^,~]*),
(don't capture the comma!) ~
instead of a comma, then go out, then go back in on the next ~
([^,~]*~[^~]*~)
In all cases, we make sure we capture enough to reconstruct the string.
I haven't tested this but I would do something like:
string sample = "Blah, blah, blah,~Part One, Part Two~,blah blah";
Regex r = new Regex("(.+)\\~(.+),(.+)\\~(.+)","${1}~${2}${3}~${4}");
r.replaceAll(sample );
I referenced Regular Expressions in Java . In here the .+ matches to one or more any character. More such patterns can be found here .
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();
Here is a method that would do the job:
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;
}
}
You can call it like this:
String a = "Blah, blah, blah,~Part One, Part Two~,blah blahBlah, blah, blah,~Part One, Part Two~,blah blah";
System.out.println(deleteCharacterBetween(a, "~", ","));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.