Android Java - String .replaceAll to replace specific characters (regex) - java

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

Related

How to split a string from the first space occurrence only Java

I tried to split a string using string.Index and string.length but I get an error that string is out of range. How can I fix that?
while (in.hasNextLine()) {
String temp = in.nextLine().replaceAll("[<>]", "");
temp.trim();
String nickname = temp.substring(temp.indexOf(' '));
String content = temp.substring(' ' + temp.length()-1);
System.out.println(content);
Use the java.lang.String split function with a limit.
String foo = "some string with spaces";
String parts[] = foo.split(" ", 2);
System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1]));
You will get:
cr: some, cdr: string with spaces
Must be some around this:
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
string.split(" ",2)
split takes a limit input restricting the number of times the pattern is applied.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex.
But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.

Java RegularExpression for " double quotes and ' ' spaces

I am trying to find and replace in the file using java but unable to get the solution.
File contents are
"ProductCode" = "8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}"
"ProductCode" = "8:.NETFramework,Version=v4.5"
I have to update the guid of first one which is 3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5
String line = "\"ProductCode\" = \"8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}\"";
String pattern = "[\"]([P][r][o][d][u][c][t][C][o][d][e]).+([\"])(\\s)[\"][8][:][{]";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
System.out.println(m.matches());
I am getting false.
please provide the solution if possible.
Thanks in advance.
"ProductCode" = "8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}" This is of the form:
quote + ProductCode + quote + whitespace + equals + whitespace +
quote + number + colon + any + quote
A simple Regex for this is \"ProductCode\"\s*=\s*\"\d:(.+)\"
When we escape this to a Java string we get \\\"ProductCode\\\"\\s*=\\s*\\\"\\d:(.+)\\\"
Try this pattern:
String pattern = "^\\\"(ProductCode)\\\"\\s\\=\\s\\\"\\w\\:\\{(\\w+\\-*\\w+\\-\\w+\\-\\w+\\-\\w+)\\}\\\"$";
Using regex for this problem is like taking a sledgehammer to break a nut. Rather simple:
final String line = "\"ProductCode\" = \"8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}\"";
final String prefix = "\"ProductCode\" = \"8:{";
final int prefixIndex = line.indexOf(prefix);
final String suffix = "}\"";
final int suffixIndex = line.indexOf(suffix);
final String guid = line.substring(prefixIndex + prefix.length(), suffixIndex);

Dangling meta character

I keep getting an error about dangling meta character when I use '+', '*', '(', and ')'.
I've already tried escaping those characters in the regex but I still get the error. This is what I have:
"[-\\+\\*/%\\(\\)]"
Update:
test:
String input = "+";
String vals = new WNScanner(input).getNextToken(); //**********
System.out.println("token: " + vals);
System.out.println(vals.matches("[-+*/%()]"));
from another class:
...
String expression = input;
...
public String getNextToken() {
String[] token = {""};
if (expression.length() == 0)
return "";
token = expression.split("\\s");
recentToken = token[0];
expression = expression.replaceFirst(token[0], ""); //*************
expression = expression.trim();
return token[0];
}
* there are exceptions on these lines.
OK, I don't know what you want to achieve there... Especially at this line:
expression = expression.replaceFirst(token[0], "");
If your input string is "+", then your whole regex is +. And that is not legal.
You need to quote the input string in order to use it in any regex-related operation, and that includes String's .replaceFirst() and .replaceAll() (but not .replace()...).
Therefore, do:
final String re = Pattern.quote(token[0]);
expression = expression.replaceFirst(re, "");

Java : Replacing Last character of a String and First character of the String

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.

Why String.replaceAll() don't work on this String?

//This source is a line read from a file
String src = "23570006,music,**,wu(),1,exam,\"Monday9,10(H2-301)\",1-10,score,";
//This sohuld be from a matcher.group() when Pattern.compile("\".*?\"")
String group = "\"Monday9,10(H2-301)\"";
src = src.replaceAll("\"", "");
group = group.replaceAll("\"", "");
String replacement = group.replaceAll(",", "##");
System.out.println(src.contains(group));
src = src.replaceAll(group, replacement);
System.out.println(group);
System.out.println(replacement);
System.out.println(src);
I'm trying to replace the "," between \"s so I can use String.split() latter.
But the above just not working , the result is:
true
Monday9,10(H2-301)
Monday9##10(H2-301)
23570006,music,**,wu(),1,exam,Monday9,10(H2-301),1-10,score,
but when I change the src string to
String src = "123\"9,10\"123";
String group = "\"9,10\"";
It works well
true
9,10
9##10
1239##10123
What's the matter with the string???
( and ) are regex metacharacter; they need to be escaped if you want to match it literally.
String group = "\"Monday9,10\\(H2-301\\)\"";
^ ^
The reason why you need two slashes is that because \ in a string literal is itself an escape character, so "\\" is a string of length 1 containing a slash.

Categories

Resources