That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)
String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");
or the equivalent:
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)
Or, with Guava:
private static final CharMatcher ALNUM =
CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);
But if you want to turn accented characters into something sensible that's still ascii, look at these questions:
- Converting Java String to ASCII
- Java change áéőűú to aeouu
- ń ǹ ň ñ ṅ ņ ṇ ṋ ṉ ̈ ɲ ƞ ᶇ ɳ ȵ --> n or Remove diacritical marks from unicode chars
That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)
String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");
or the equivalent:
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)
Or, with Guava:
private static final CharMatcher ALNUM =
CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);
But if you want to turn accented characters into something sensible that's still ascii, look at these questions:
- Converting Java String to ASCII
- Java change áéőűú to aeouu
- ń ǹ ň ñ ṅ ņ ṇ ṋ ṉ ̈ ɲ ƞ ᶇ ɳ ȵ --> n or Remove diacritical marks from unicode chars
I am using this.
s = s.replaceAll("\\W", "");
It replace all special characters from string.
Here
\w : A word character, short for [a-zA-Z_0-9]
\W : A non-word character
This worked for me:
String result = str.replaceAll("[^\\dA-Za-z ]", "").replaceAll("\\s+", "+");
For this input string:
/-+!@#$%^&())";:[]{}\ |wetyk 678dfgh
It yielded this result:
+wetyk+678dfgh
replaceAll expects a regex:
public static final String specialChars2 = "[`~!@#$%^&*()_+[\\]\\\\;\',./{}|:\"<>?]";
use [\\W+] or "[^a-zA-Z0-9]" as regex to match any special characters and also use String.replaceAll(regex, String) to replace the spl charecter with an empty string. remember as the first arg of String.replaceAll is a regex you have to escape it with a backslash to treat em as a literal charcter.
String c= "hjdg$h&jk8^i0ssh6";
Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
Matcher match= pt.matcher(c);
while(match.find())
{
String s= match.group();
c=c.replaceAll("\\"+s, "");
}
System.out.println(c);
You can read the lines and replace all special characters safely this way.
Keep in mind that if you use \\W you will not replace underscores.
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()){
System.out.println(scan.nextLine().replaceAll("[^a-zA-Z0-9]", ""));
}
Simply use String#replace(CharSequence target, CharSequence replacement) in your case to replace a given CharSequence, as next:
special = special.replace("@$", "as");
Or use Pattern.quote(String s) to convert your String as a literal pattern String, as next:
special = special.replaceAll(Pattern.quote("@$"), "as");
If you intend to do it very frequently, consider reusing the corresponding Pattern instance (the class Pattern is thread-safe which means that you can share instances of this class) to avoid compiling your regular expression at each call which has a price in term of performances.
So your code could be:
private static final Pattern PATTERN = Pattern.compile("@$", Pattern.LITERAL);
...
special = PATTERN.matcher(special).replaceAll("as");
Escape characters:-
String special = "Something @$ great @$ that.";
special = special.replaceAll("@\\$", "as");
System.out.println(special);
For Regular Expression, below 12 characters are reserved called as metacharacters. If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash.
the backslash \
the caret ^
the dollar sign $
the period or dot .
the vertical bar or pipe symbol |
the question mark ?
the asterisk or star *
the plus sign +
the opening parenthesis (
the closing parenthesis )
the opening square bracket [
and the opening curly brace {
references:- http://www.regular-expressions.info/characters.html
You could use a lookahead, to find the end of the string, preceded by characters other than dot.
yourString.replaceAll("\\.(?=[^.]*$)", "replacement");
Note that the first dot needs to be escaped with a backslash, because dot has a special meaning in a regular expression (it matches any character). The second dot doesn't need to be escaped, because the special meaning doesn't apply in square brackets.
The (?= ) structure means "followed by this" - in other words, the dot that you match can be followed by any number of non-dot characters, and then the end of the string. Those extra characters are not considered part of the match.
It's not a regex, but you could use the String.lastIndexOf() method to get the position of the last occurence of your char and use String.substring to create your new String:
String yourString = "test.csv";
String newValue = "_2.";
int lastOccurence = yourString.lastIndexOf(".");
String replacedString = yourString.substring(0, lastOccurence) + newValue + yourString.substring(lastOccurence + 1);
You need to:
- replace all commas within quotes with +
- replace non-whitelist (and you need to add commas to your whitelist) +
- remove double quotes
Try this:
line = line.replaceAll("[^A-Za-z0-9\",]|,(?!(([^\"]*\"){2})*[^\"]*$)", "+").replace("\"", "");
I think your regex is pretty close. Add an exception for comma's as well and get rid of the space and you are good.
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = r.readLine()) != null)
{
String replaced = line.replace("\"", "");
replaced = replaced.replaceAll("[^A-Za-z0-9,]", "+");
System.out.println(replaced);
}
Of course, Strings are immutable in Java. Keep that in mind. replaceAll() returns a new String and does not modify the original instance.
Demo here.
Replace any sequence of non-letters with a single white space:
str.replaceAll("[^a-zA-Z]+", " ")
You also might want to apply trim() after the replace.
If you want to support languages other than English, use "[^\\p{IsAlphabetic}]+" or "[^\\p{IsLetter}]+". See this question about the differences.
The OR operator (|) should work:
System.out.println(str.replaceAll("([^a-zA-Z]|\\s)+", " "));
Actually, the space doesn't have to be there at all:
System.out.println(str.replaceAll("[^a-zA-Z]+", " "));
You can get rid of all characters outside the printable ASCII range using String#replaceAll() by replacing the pattern [^\\x20-\\x7e] with an empty string:
a = a.replaceAll("[^\\x20-\\x7e]", "");
But this actually doesn't solve your actual problem. It's more a workaround. With the given information it's hard to nail down the root cause of this problem, but reading either of those articles must help a lot:
- The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
- Unicode - How to get the characters right?
It is hard to answer the question without knowing more of the context.
In general you might have an encoding problem. See The Absolute Minimum Every Software Developer (...) Must Know About Unicode and Character Sets for an overview about character encodings.
Use replaceAll("[^\\w\\s\\-_]", "");
What I did was add the underscore and hyphen to the regular expression. I added a \\ before the hyphen because it also serves for specifying ranges: a-z means all letters between a and z. Escaping it with \\ makes sure it is treated as an hyphen.
This might help:
replaceAll("[^a-zA-Z0-9_-]", "");