如何使用正则表达式

时间:2016-11-08 19:38:41

标签: java regex arraylist

如何使用正则表达式检查JTextField是否仅包含大小写字母和' - ',然后将其添加到ArrayList?我到处都看了,大多数地方都说同样的话,但我无法弄清楚我错过了什么。以下是出现问题的代码片段:

public static void AddArray(ArrayList arrayWords, JTextField textFieldEntry, JLabel labelWords){
    String textFieldValueRed = textFieldEntry.getText();

//Check that textfield only contains letters and '-'
    Pattern p= Pattern.compile("[a-zA-Z-]");
    Matcher m = p.matcher(textFieldEntry.toString());
    boolean b = m.matches();
    if (b==true){
        arrayWords.add(textFieldEntry.getText().toString());
        labelWords.setText("'"+textFieldEntry.getText()+"' was added to list.");
    }
    else{
        labelWords.setText("The string ‘"+textFieldEntry.getText()+"’ was not added to the list as it is not a valid word.");
    }
}

1 个答案:

答案 0 :(得分:2)

您必须使用+至少一个或多个值

Pattern.compile("[a-zA-Z-]+");

如果只有单个字符

,则此[a-zA-Z-]将匹配为true

[]将仅匹配其中定义的单个值

+表示会有一个或多个值,因此它匹配前一个令牌的一次或多次出现。

更新:另一个问题是,您需要使用StringtextFieldValueRed,而getText()使用textFieldEntry.toString()函数而不是textFieldEntry.toString(),因为此Matcher m = p.matcher(textFieldEntry.getText()); 会给出一些意想不到的值,即类签名和哈希码,所以按照这个

public static void AddArray(ArrayList arrayWords, JTextField textFieldEntry, JLabel labelWords){

    Pattern p = Pattern.compile("[a-zA-Z-]+");
    Matcher m = p.matcher(textFieldEntry.getText());
    if (m.matches()){
        arrayWords.add(textFieldEntry.getText());
        labelWords.setText("'"+textFieldEntry.getText()+"' was added to list.");
    }
    else{
        labelWords.setText("The string ‘"+textFieldEntry.getText()+"’ was not added to the list as it is not a valid word.");
    }
}

完整代码

Pattern

或者在不创建任何 if (textFieldEntry.getText().trim().matches("[a-zA-Z-]+")){ arrayWords.add(textFieldEntry.getText()); labelWords.setText("'"+textFieldEntry.getText()+"' was added to list."); } else{ labelWords.setText("The string ‘"+textFieldEntry.getText()+"’ was not added to the list as it is not a valid word."); } 对象

的情况下执行此操作
{{1}}