I want to remove "[", "]", "," from my string
for example,
[569.24, 569.24, 568.10, 566.00, 566.01, 566.00, 567.98, 565.14]
to
569.24 569.24 568.10 566.00 566.01 566.00 567.98 565.14
however, I can remove "," but "[" and "]"
my codes are as follows.
String content = price_result.toString();
//remove special characters
String content_modified = content.replaceAll("[ \t\"',;]+", " ");
System.out.println(content_modified);
the above result in [569.24, 569.24, 568.10, 566.00, 566.01, 566.00, 567.98, 565.14]..
How can I remove "[" and "]"?
just use this
String content = price_result.toString();
//remove special characters
String content_modified = content.replace("[","").replace("]","").replace(",","");
System.out.println(content_modified);
You can try the next:
// Characters you want to remove
String unwanted = "[],";
// It will be used frequently? Use a constant.
Pattern pattern = Pattern.compile("[" + Pattern.quote(unwanted) + "]");
String content = price_result.toString();
String content_modified = pattern.matcher(content).replaceAll("");
System.out.println(content_modified);
Put them in character class [] with escape character \
String content_modified = content.replaceAll("[\\[\t\"',;\\]]+", " ");
Or pipe them one by one(put other characters yourself :)
String content_modified = content.replaceAll("\\[|\\]|,|;", " ");
Related
final String remove = " " // tab is 3 spaces
while (lineOfText != null)
{
if (lineOfText.contains(remove))
{
lineOfText = " ";
}
outputFile.println(lineOfText);
lineOfText = inputFile.readLine();
}
I tried running this but it doesn't replace the tabs with one blank space. Any solutions?
Tab is not three spaces. It's a special character that you obtain with an escape, specifically final String remove = "\t"; and
if (lineOfText.contains(remove))
lineOfText = lineOfText.replaceAll(remove, " ");
}
or remove the if (because replaceAll doesn't need it) like,
lineOfText = lineOfText.replaceAll(remove, " ");
You can simply use this regular expression to replace any type of escapes( including tabs, newlines, spaces etc.) within a String with the desired one:
lineOfText.replaceAll("\\s", " ");
Here in this example in the string named lineOfText we have replaced all escapes with whitespaces.
I have a string from which I need to remove all mentioned punctuations and spaces. My code looks as follows:
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s+]");
System.out.println("spart[0]: " + spart[0]);
System.out.println("spart[1]: " + spart[1]);
System.out.println("spart[2]: " + spart[2]);
System.out.println("spart[3]: " + spart[3]);
I have a string from which I need to remove all mentioned punctuations and spaces. My code looks as follows:
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s+]");
System.out.println("spart[0]: " + spart[0]);
System.out.println("spart[1]: " + spart[1]);
System.out.println("spart[2]: " + spart[2]);
System.out.println("spart[3]: " + spart[3]);
But, I am getting some elements which are blank. The output is:
spart[0]: s
spart[1]: film
spart[2]:
spart[3]: normal
- is a special character in PHP character classes. For instance, [a-z] matches all chars from a to z inclusive. Note that you've got )-_ in your regex.
- defines a range in regular expressions as used by String.split argument so that needs to be escaped
String[] part = line.toLowerCase().split("[,/?:;\"{}()\\-_+*=|<>!`~##$%^&]");
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s]+");
I need to remove some specific "special" characters and replace them with empty string if they show up.
I am currently having a problem with the regex, probably with the Java escaping. I can't put them all together, it just doesn't work, I tried a lot! T_T
Currently I am doing it one by one which is kinda silly, but for now at least it works, like that :
public static String filterSpecialCharacters(String string) {
string = string.replaceAll("-", "");
string = string.replaceAll("\\[", "");
string = string.replaceAll("\\]", "");
string = string.replaceAll("\\^", "");
string = string.replaceAll("/", "");
string = string.replaceAll(",", "");
string = string.replaceAll("'", "");
string = string.replaceAll("\\*", "");
string = string.replaceAll(":", "");
string = string.replaceAll("\\.", "");
string = string.replaceAll("!", "");
string = string.replaceAll(">", "");
string = string.replaceAll("<", "");
string = string.replaceAll("~", "");
string = string.replaceAll("#", "");
string = string.replaceAll("#", "");
string = string.replaceAll("$", "");
string = string.replaceAll("%", "");
string = string.replaceAll("\\+", "");
string = string.replaceAll("=", "");
string = string.replaceAll("\\?", "");
string = string.replaceAll("|", "");
string = string.replaceAll("\"", "");
string = string.replaceAll("\\\\", "");
string = string.replaceAll("\\)", "");
string = string.replaceAll("\\(", "");
return string;
}
Those are all the character I need to remove:
- [ ] ^ / , ' * : . ! > < ~ # # $ % + = ? | " \ ) (
I am clearly missing something, I can't figure out how to put it all in one line. Help?
Your code does not work in fact because .replaceAll("$", "") replaces an end of string with empty string. To replace a literal $, you need to escape it. Same issue is with the pipe symbol removal.
All you need to do is to put the characters you need to replace into a character class and apply the + quantifier for better performance, like this:
string = string.replaceAll("[-\\[\\]^/,'*:.!><~##$%+=?|\"\\\\()]+", "");
Note that inside a character class, most "special regex metacharacters" lose their special status, you only have to escape [, ], \, a hyphen (if it is not at the start/end of the character class), and a ^ (if it is the first symbol in the "positive" character class).
DEMO:
String s = "-[]^/,'*:.!><~##$%+=?|\"\\()TEXT";
s = s.replaceAll("[-\\[\\]^/,'*:.!><~##$%+=?|\"\\\\()]+", "");
System.out.println(s); // => TEXT
Use these codes
String REGEX = "YOUR_REGEX";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(yourString);
yourString = m.replaceAll("");
UPDATE :
Your REGEX looks something like
String REGEX = "-|\\[|\\]|\\^|\\/|,|'|\\*|\\:|\\.|!|>|<|\\~|#|#|\\$|%|\\+|=\\?|\\||\\\\|\\\\\\\\|\\)|\\(";
SAPMLE :
String yourString = "#My (name) -is #someth\ing"";
//Use Above codes
Log.d("yourString",yourString);
OUTPUT
How to detect the letters in a String and switch them?
I thought about something like this...but is this possible?
//For example:
String main = hello/bye;
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
}else{
//nothing
}
Well, if you are interested in a cheeky regex :P
public static void main(String[] args) {
String s = "hello/bye";
//if(s.contains("/")){ No need to check this
System.out.println(s.replaceAll("(.*?)/(.*)", "$2/$1")); // () is a capturing group. it captures everything inside the braces. $1 and $2 are the captured values. You capture values and then swap them. :P
//}
}
O/P :
bye/hello --> This is what you want right?
Use String.substring:
main = main.substring(main.indexOf("/") + 1)
+ "/"
+ main.substring(0, main.indexOf("/")) ;
You can use String.split e.g.
String main = "hello/bye";
String[] splitUp = main.split("/"); // Now you have two strings in the array.
String newString = splitUp[1] + "/" + splitUp[0];
Of course you have to also implement some error handling when there is no slash etc..
you can use string.split(separator,limit)
limit : Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array
String main ="hello/bye";
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
String[] parts = main.split("/",1);
main = parts[1] +"/" + parts[0] ; //main become 'bye/hello'
}else{
//nothing
}
Also you can use StringTokenizer to split the string.
String main = "hello/bye";
StringTokenizer st = new StringTokenizer(main,"\");
String part1 = st.nextToken();
String part2 = st.nextToken();
String newMain = part2 + "\" + part1;
I want to add Two java JSON String manually , so for this i need to remove "}" and replace it with comma "," of first JSON String and remove the first "{" of the second JSON String .
This is my program
import java.util.Map;
import org.codehaus.jackson.type.TypeReference;
public class Hi {
private static JsonHelper jsonHelper = JsonHelper.getInstance();
public static void main(String[] args) throws Exception {
Map<String, Tracker> allCusts = null;
String A = "{\"user5\":{\"Iden\":4,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
String B = "{\"user1\":{\"Iden\":4,\"Num\":1},\"user3\":{\"Iden\":6,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
String totalString = A + B;
if (null != totalString) {
allCusts = (Map<String, Tracker>) jsonHelper.toObject(
totalString, new TypeReference<Map<String, Tracker>>() {
});
}
System.out.println(allCusts);
}
}
When adding two Strings A + B
I want to remove the last character of "}" in A and replace it with "," and remove the FIrst character of "{" in B .
SO this should it look like .
String A = "{\"user5\":{\"Iden\":4,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1},";
String B = "\"user1\":{\"Iden\":4,\"Num\":1},\"user3\":{\"Iden\":6,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
I have tried
String Astr = A.replace(A.substring(A.length()-1), ",");
String Bstr = B.replaceFirst("{", "");
String totalString = Astr + Bstr ;
With this i was getting
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
please suggest .
{ is a control character for Regular Expressions, and since replaceFirst takes a string representation of a Regular Expression as its first argument, you need to escape the { so it's not treated as a control character:
String Bstr = B.replaceFirst("\\{", "");
I would say that using the replace methods is really overkill here since you're just trying to chop a character off of either end of a string. This should work just as well:
String totalString = A.substring(0, A.length()-1) + "," + B.substring(1);
Of course, regex doesn't look like a very good tool for this. But the following seem to work:
String str = "{..{...}..}}";
str = str.replaceFirst("\\{", "");
str = str.replaceFirst("}$", ",");
System.out.println(str);
Output:
..{...}..},
Some issues in your first two statements. Add 0 as start index in substring method and leave with that. Put \\ as escape char in matching pattern and ut a , in second statement as replacement value.
String Astr = A.substring(0, A.length()-1);//truncate the ending `}`
String Bstr = B.replaceFirst("\\{", ",");//replaces first '{` with a ','
String totalString = Astr + Bstr ;
Please note: There are better ways, but I am just trying to correct your statements.