alpha 和空格的 java 正则表达式包括 [] \

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12761231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:06:17  来源:igfitidea点击:

java regex for alpha and spaces is including [ ] \

javaregex

提问by KisnardOnline

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??

这是我的 JTextField 的正则表达式,不超过 x 个字符,并且不包含字母或空格以外的任何内容。 出于某种原因,它允许 [ ] 和 \ 字符。这真让我抓狂。我的正则表达式错了吗??

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);
        }
    }
}

回答by Alan Moore

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 Zand a.

[A-z]匹配所有大写和小写字母[]^_、反斜杠和反引号,其代码点恰好位于Z和之间a

Also, I agree with @?mega that you probably should be using an actual space character instead of \s:

另外,我同意 @?mega 您可能应该使用实际的空格字符而不是\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.

锚点 (^$) 不是必需的,因为您使用的是该matches()方法,该方法会自动在两端锚定匹配项。不过,它们不会伤害任何东西,它们确实有助于传达您的意图。

回答by ?mega

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 5characters and maximum 20characters

您还可以扩展此类正则表达式以检查字符串大小。假设您想允许最少5字符数和最多20字符数

^[a-zA-Z\s]{5,20}$


However, because whitespace \\scan 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

但是,因为空白不仅\\s可以是空格字符,还可以是其他字符,例如换行符、制表符等,您可能希望将其限制为真正的空格字符,使用

 ^[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]$

回答by John Woo

reformat your regex into this:

将您的正则表达式重新格式化为:

^[A-Za-z\s]{0,3}$

just change 3 to your desired length.

只需将 3 更改为您想要的长度。