Reputation: 740
This is my regex for my JTextField to not be longer than x characters and to not include anything other than letters or spaces. For some reason it is allowing [ ] and \ characters. This is driving me crazy. Is my regex wrong??
package com.jayavon.game.helper;
import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class CharacterNameCreationDocument extends PlainDocument {
private static final long serialVersionUID = 1L;
private int limit;
public CharacterNameCreationDocument(int limit) {
super();
this.limit = limit;
}
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
if (str == null || (getLength() + str.length()) > limit || !str.matches("[a-zA-z\\s]*")){
Toolkit.getDefaultToolkit().beep();
return;
} else {
super.insertString(offset, str, attr);
}
}
}
Upvotes: 3
Views: 23615
Reputation: 75222
You have a typo in your regex:
"[a-zA-z\\s]*"
[A-z]
matches all the uppercase and lowercase letters plus [
, ]
, ^
, _
, backslash and backtick, whose code points happen to lie between Z
and a
.
Also, I agree with @Ωmega that you probably should be using an actual space character instead of \s
:
"[a-zA-Z ]*"
The anchors (^
and $
) aren't necessary since you're using the matches()
method, which automatically anchors the match at both ends. They don't hurt anything though, and they do help communicate your intent.
Upvotes: 8
Reputation: 43673
You should use regex pattern
^[a-zA-Z\\s]*$
where ^
is start of string and $
represents end of string.
You can also extend such regex to check the string size. Let's say if you want allow minimum 5
characters and maximum 20
characters
^[a-zA-Z\\s]{5,20}$
However, because whitespace \\s
can be not just space-bar character, but also other charactes, such as new-line, tab, etc., you may want to limit this just to real space-bar characters using
^[a-zA-Z ]{5,20}$
Additionaly, you might want to limit multiple space characters to be used in sequence. If so, use
^(?!.* {2,})[a-zA-Z ]{5,20}$`
You might want string always to start and end with non-space characters. To add such feature go with
^(?=.{5,20}$)(?!.* {2,})[a-zA-Z][a-zA-Z ]*[a-zA-Z]$
Upvotes: 7
Reputation: 263713
reformat your regex into this:
^[A-Za-z\\s]{0,3}$
just change 3 to your desired length.
Upvotes: 1