gpt4 book ai didi

java - 字符串的正则表达式模式至少 4 个字符,在字符串末尾包含特定字符

转载 作者:行者123 更新时间:2023-12-01 17:56:31 24 4
gpt4 key购买 nike

我正在尝试为以下情况创建正则表达式模式:

The String must contain the character '%' once and only once as the last character of the String. The String must be at least 4 characters including the '%'. The String can only be a max of 35 chars(including the %)

我目前有这个模式:[^~,]{3,}[$%]涵盖除重复 % 之外的所有情况字符。

如何在我的正则表达式中明确地说:“作为字符串中的最后一个字符出现一次且仅一次”

一些带有.matches(<regex_pattern>) results的例子

  • ABC% -> 正确
  • AB% -> 错误
  • ABCDEFGHIJKLMN% -> 正确
  • AB%C% -> 错误
  • %ABC% -> 错误
  • @!#$% -> 正确
  • ABCDEFGHIJKLMNOPQRSTUVXYZABCDEFGHIJ% -> FALSE(36 个字符 + 百分比 = 36)

最佳答案

听起来您只需要:

^[^%]{3,34}%$

这意味着:

  • 字符串的开头
  • 后跟 3 到 34 个非 % 的字符
  • 后跟%
  • 后跟字符串结尾

(根据您如何使用此正则表达式,可能不需要显式开始和结束 anchor ^$)

我认为值得指出的是,正则表达式不是必需的,并且没有正则表达式可以产生更易读的条件:

boolean matches =
str.length() >= 4
&& str.length() <= 35
&& str.endsWith("%")
&& str.indexOf("%") == str.length() - 1;

关于java - 字符串的正则表达式模式至少 4 个字符,在字符串末尾包含特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44337041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com