Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

Java正则匹配ASCII码且不能包含中文,最多4个字符

  1. User

    Java正则匹配ASCII码且不能包含中文,最多4个字符

  2. Assistant

    要使用Java正则表达式匹配ASCII码且不能包含中文的字符串,最多4个字符,可以使用以下正则表达式:

    ^[\\x00-\\x7F]{1,4}$
    

    这个正则表达式可以匹配任意ASCII码字符,并限制最多4个字符。这里的\\x00-\\x7F表示ASCII码的范围。

    下面是一个示例代码:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
        public static void main(String[] args) {
            String[] strings = {"abcd", "1234", "中文", "$%^&"};
    
            Pattern pattern = Pattern.compile("^[\\x00-\\x7F]{1,4}$");
    
            for (String str : strings) {
                Matcher matcher = pattern.matcher(str);
                if (matcher.matches()) {
                    System.out.println(str + " 匹配成功");
                } else {
                    System.out.println(str + " 匹配失败");
                }
            }
        }
    }
    

    输出结果为:

    abcd 匹配成功
    1234 匹配成功
    中文 匹配失败
    $%^& 匹配成功
    

    注意:这个正则表达式只能匹配ASCII码字符,并且限制最多4个字符,如果要匹配其他字符集和不同长度的字符串,需要相应地修改正则表达式。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.