Reputation: 1046
I'm trying to strip the symbols from my Strings and this isn't working. It's like Pattern Matcher seems broke. I know I'm just missing something. Thanks.
Pattern p = Pattern.compile("[,\\.;:{}/\\[\\]<>?`~!@#$%^&*()_+=]");
Matcher m = p.matcher("April's");
Matcher m1 = p.matcher("Place to go!");
setName(m.replaceAll(""));
setDescription(m1.replaceAll(""));
I'm expected to see this:
Input- "Sarah's Scope"
Output- "Sarahs Scope"
What I'm currently seeing is:
Input- "Sarah's Scope"
Output- "Sarah's Scope"
Upvotes: 0
Views: 82
Reputation: 26370
Use this pattern instead:
"[\\'\\\",\\.;:{}/\\[\\]<>\\?`~!@#\\$%\\^&\\*\\(\\)_\\+=]"
or thi:
"[\\'\\\",\\.;:{}/\\[\\]<>\\?\\`~!@#\\$%\\^&\\*\\(\\)_\\+=]"
But maybe it would be easier to do with:
"[^[a-z][A-Z][0-9]]"
or
"[^a-zA-Z0-9]"
since you are searching any symbol it would be any character except letters and numbers.
Upvotes: 1
Reputation: 785098
I believe you're looking for \\p{Punct}
regex property here to weed out all punctuation characters:
Consider this code:
Pattern p = Pattern.compile("\\p{Punct}+");
Matcher m = p.matcher("Sarah's Scope");
System.out.println(m.replaceAll(""));
//> Sarahs Scope
Upvotes: 0
Reputation: 25297
It looks like you are trying to strip all characters that aren't letters or whitespace. If that is the case, then this will work:
"[^\\sA-Za-z]"
Or, if you want to include numbers:
"[^\\sA-Za-z0-9]"
Or, if you know specifically what you want to keep: "[^
followed by what you want to keep, then followed by ]"
.
If you are just trying to remove all characters of a String
that don't match the pattern, then it is easier to use String.replaceAll()
.
For more on regex, see regex tutorial.
Upvotes: 0