用正则表达式我也刚开始学,看jdk就可以了 public class RegexTest { public static void main(String[] args) { String test = "_-._"; Pattern p = Pattern.compile("\\w*[-._]*"); Matcher m = p.matcher(test); boolean b = m.matches(); if (b) { System.out.println("right"); } else { System.out.println("wrong"); } } }
如果是限制TextField的输入类别,可以参考一下我的这个类 /** * this class is used to restrict the input, it makes sure that * the text of the text field is a digit string.that is, 'a','Z', * '_','$'and so on are all forbidden. * @author feng * */ private class OnlyDigit extends PlainDocument{ private JTextField f; public OnlyDigit(JTextField f){ this.f = f; } public void insertString(int offset, String str, AttributeSet attSet) throws BadLocationException{ StringBuffer tmp = new StringBuffer(f.getText()); tmp.insert(offset,str); Pattern p = Pattern.compile("^-?\\d*(\\.)?\\d*$"); Matcher m = p.matcher(tmp.toString()); if(m.find()){ super.insertString(offset,str,attSet); } } }... a.setDocument(new OnlyDigit(a));//a is a JTextField reference
http://buy.ccw.cn/htm/app/aprog/01_7_31_4.asp
public class RegexTest {
public static void main(String[] args) {
String test = "_-._";
Pattern p = Pattern.compile("\\w*[-._]*");
Matcher m = p.matcher(test);
boolean b = m.matches();
if (b) {
System.out.println("right");
} else {
System.out.println("wrong");
}
}
}
alert("输入的格式不正确。手机型号只能由字母、数字、空格符、横线及下划线组成.");
return false;
}
alert("*****************");
window.document.form1.**.focus();
return;
}
/**
* this class is used to restrict the input, it makes sure that
* the text of the text field is a digit string.that is, 'a','Z',
* '_','$'and so on are all forbidden.
* @author feng
*
*/
private class OnlyDigit extends PlainDocument{
private JTextField f; public OnlyDigit(JTextField f){
this.f = f;
}
public void insertString(int offset,
String str,
AttributeSet attSet)
throws BadLocationException{
StringBuffer tmp = new StringBuffer(f.getText());
tmp.insert(offset,str);
Pattern p = Pattern.compile("^-?\\d*(\\.)?\\d*$");
Matcher m = p.matcher(tmp.toString());
if(m.find()){
super.insertString(offset,str,attSet);
}
}
}...
a.setDocument(new OnlyDigit(a));//a is a JTextField reference