Reputation: 367
I am coding in Java here.
I know that the regex for matching any number or string of letter is
"(0|[1-9][0-9]*)(\\.[0-9]+)?|[a-zA-Z]+"
But I would like to match anything except letter or number, ie symbols like !, @, +, -
I tried doing [^.. ]
but it doesn't work.
For example, let's say I want to do the opposite, ie return all parts of the string that contains numbers or strings of letters or @, I would do
public ArrayList<String> findMatch(String string){
ArrayList <String> outputArr = new ArrayList<String>();
Pattern p = Pattern.compile("(0|[1-9][0-9]*)(\\.[0-9]+)?|[a-zA-Z]+|\\@");
// recognizes number, string, and @
Matcher m = p.matcher(string)
while (m.find()) {
outputArr.add(m.group());
}
return outputArr;
}
Let's say I want to find the opposite of the code above, how can I change line 3?
Upvotes: 0
Views: 1341
Reputation: 7804
The simplest regex pattern that you can use is : [^\w]+ This will match all the special characters which are neither numbers nor alphabets. Hope this helps. This is a sample Regex Tester with sample examples. You can test your regex for correctness over here. Hope this will help you.
From the example you have provided what I understand is, you want all the characters except alphabets, numbers and '@'.
In regex '\w' matches any alphabet(including underscore) and any number. So you need to negate this, to get other symbolic characters like '$,#' etc.
Below expression will solve your issue = [^\w@]+
'^' indicate negation symbol. Here '^\w' meaning 'match anything except alphabets or numbers'. I have also added '@' symbol in the expression as you need to ignore it as well.
Hope this will answer your question.
Upvotes: 1
Reputation: 3512
If you can give some more detail, what is your requirement? and what you expect? It will help me to figure out the solution. What you put in your query looks like you want to match special characters only. Am I right? If so you can just try:
[^A-Za-z0-9][your quantifier here]
quantifier can be:
? for 0 or 1 frequency
+ for >=1 frequency
* for >=0 frequency
Suppose you have a String like
String s="shyuit6785%^7kui!@*&123f#$annds";
//And you want to find out the characters except alphabets and numerals . (I hope its your requirement)
Pattern p = Pattern.compile("[^A-Za-z0-9@]+");
Matcher m = p.matcher(s);
while (m.find())
{
System.out.println("Found a required character " + m.group() + " at index number " +m.start());
}
Upvotes: 0
Reputation: 5607
You'll probably want to use just this:
\W+
That will match a string of any characters that aren't "word characters", defined as:
[a-zA-Z0-9_]
or "all letters, numbers, and underscore". If you want to include underscore, try the following:
[\W_]+
Or, if you'd rather have it explicit:
[^A-Za-z0-9]+
Which means "everything but letters and numbers".
Hope this helps.
Upvotes: 2