正则表达式中字符集的问题,字符串开头和结尾的固定长度和步幅

Issue in Regex for set for characters, fixed length and paces at beginning and ending of a string

最初,我有一个要求,我应该检查给定的字符串是否遵循以下两种模式。

早些时候我们要在字符串不匹配时给出两条不同的消息,所以我处理如下:

    Pattern pattern1 = Pattern.compile("^(.{1,5})?$");
    Pattern pattern2 = Pattern.compile("[!-~]|([!-~][ -~]*[!-~])");
    Matcher matcher1=pattern1.matcher(" verify");
    Matcher matcher2 = pattern2.matcher("verify");
    System.out.println("Message1 - " + matcher1.matches());
    System.out.println("Message2 - " + matcher2.matches());

但现在的要求是我们需要: --我们需要合并上述两种模式但是

--还包括字符串可以包含以下字符 $, #,@ 除了字母,数字

--并给出一条消息。

我看了很多类似的问题,比如: regex for no whitespace at the begining and at the end but allow in the middlehttps://regex101.com/ 制作单个正则表达式,如 :

Pattern pattern3=Pattern.compile(
  "^[^\\s][[-a-zA-Z0-9-()@#$]+(\\s+[-a-zA-Z0-9-()@#$]+)][^\\s]{1,50}$");

但是正则表达式无法正常工作。 如果我提供一个字符串,其中包含正则表达式中未提及的字符,如“%”,它应该会失败,但它会通过。

我想弄清楚上面的正则表达式或任何可以满足需要的新正则表达式中的问题。

@编辑更清楚: 有效输入:"Hell@"

无效输入:“Hell”(有空白@beginning)

无效输入:"Hell%" conatins 不需要 char '%'

这里有一个模式应该可以满足您的两个要求:

^\S(?:.{0,3}\S)?$

这表示匹配:

\S        an initial non whitespace character
(
    .{0,3}    zero to three of any character (whitespace or non whitespace)
    \S        a mandatory ending whitespace character
)?        the entire quantity optional

Demo

您可以使用这个正则表达式:

^(?!\s)[a-zA-Z\d$#@ ]{1,5}(?<!\s)$

RegEx Demo

正则表达式详细信息:

  • ^: 开始
  • (?!\s):否定前瞻,不允许space开始
  • [a-zA-Z\d$#@ ]{1,5}: 允许这些字符的长度在 1 到 5 之间
  • (?<!\s):负向后看,不允许space在结束
  • 之前
  • $:结束