You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则表达式转义特殊字符及限制字符串结尾非空格/点的实现疑问

Fixing the Filename Validation Regex

Got it, let's tweak your regex to cover both the forbidden characters and the trailing space/dot restriction. Here's how to do it properly:

First, let's recap your requirements clearly:

  • No forbidden characters: <, >, :, ", /, \, |, ?, *, \0 (null character)
  • Cannot end with a space or a dot (.)

The Updated Regex

Instead of just checking for forbidden characters with find(), we need to validate the entire string to ensure it meets all rules. Here's the corrected pattern (with Java-specific escaping):

Pattern.compile("^[^<>:\"/\\\\|?*\\0]*[^ .]$")

Breaking Down the Regex

Let's break this down so you understand each part:

  • ^: Anchors the match to the start of the string
  • [^<>:\"/\\\\|?*\\0]*: Matches 0 or more characters that are not in the forbidden list (the ^ inside the brackets means "not")
  • [^ .]$: Ensures the last character (anchored to the end with $) is not a space or dot
  • The entire pattern ensures every character is allowed, and the final character doesn't violate the trailing rule

Updated Code Implementation

Your original code used find() which only checks if any forbidden character exists. We need to use matches() to validate the whole string, then invert the result to keep your original logic (return true if the name is invalid):

import java.util.regex.Pattern;

public class NameValidator {
    // Precompile the pattern for efficiency
    private static final Pattern VALID_NAME_PATTERN = Pattern.compile("^[^<>:\"/\\\\|?*\\0]*[^ .]$");

    public static boolean isInvalidName(String name) {
        // Return true if the name DOES NOT match the valid pattern
        return !VALID_NAME_PATTERN.matcher(name).matches();
    }
}

Optional: Disallow Empty Strings

If you want to prevent empty names (since an empty string would technically pass the above regex), change the * to + to require at least one valid character:

Pattern.compile("^[^<>:\"/\\\\|?*\\0]+[^ .]$")

Notes

  • I removed the single quote (') from the forbidden list since it wasn't in your original requirements—add it back inside the first bracket if you need to block it too.
  • The \\0 in the regex escapes the null character properly for Java.

内容的提问来源于stack exchange,提问作者Noman Arshad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:09:20