gpt4 book ai didi

java - Java 标识符的正则表达式优化。将结尾的数字与其他部分分开

转载 作者:行者123 更新时间:2023-11-30 06:35:21 25 4
gpt4 key购买 nike

我需要读取一个字符串作为有效的 Java 标识符,并分别获取结尾部分(如果有)和开始部分的数字。

a1 -> a,1
a -> a,
a123b -> a123b,
ab123 -> ab, 123
a123b456 -> a123b, 456
a123b456c789 -> a123b456c, 789
_a123b456c789 -> _a123b456c, 789

我编写了一对正则表达式,并在 http://www.regexplanet.com/advanced/java/index.html 上进行了测试,它们看起来工作正常

([a-zA-Z_][a-zA-Z0-9_]*[a-zA-Z_]|[a-zA-Z_])(\d+)$
([a-zA-Z_](?:[a-zA-Z0-9_]*[a-zA-Z_])?)(\d+)$

如何缩短它们?或者你可以建议另一个正则表达式吗?

我无法将 [a-zA-Z_] 更改为\w,因为最后一个也需要数字。

(我们正在讨论在 Java/Groovy 中将\替换为\\之前的正则表达式字符串)

最佳答案

Incremental Java 说:

  • Each identifier must have at least one character.
  • The first character must be picked from: alpha, underscore, or dollar sign. The first character can not be a digit.
  • The rest of the characters (besides the first) can be from: alpha, digit, underscore, or dollar sign. In other words, it can be any valid identifier character.

    Put simply, an identifier is one or more characters selected from alpha, digit, underscore, or dollar sign. The only restriction is the first character can't be a digit.

Java docs 还添加:

The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all.

您可以使用这个可用于匹配任何有效变量并将起始字符 block 放入一组并将所有尾随数字放入另一组:

^(?!\d)([$\w]+?)(\d*)$

查看 regex demo

或者这个仅匹配遵循约定的标识符:

^(?![\d_])(\w+?)(\d*)$

参见 this regex demo

详细信息:

  • ^ - 字符串开头
  • (?!\d) - 第一个字符不能是数字((?![\d_]) 如果第一个字符是数字,则匹配失败或_)
  • ([$\w]+?) - 第 1 组:一个或多个单词或 $ 字符((\w+?) 将只匹配字母/数字/_ 字符),尽可能少(因为 +? 是一个惰性量词),最多可达第一次出现...
  • (\d*)$ - 第 2 组:字符串末尾有零个或多个数字 ($)。

Groovy demo:

// Non-convention Java identifier
def res = 'a123b$456_c789' =~ /^(?!\d)([$\w]+?)(\d*)$/
print("${res[0][1]} : ${res[0][2]}") // => a123b$456_c : 789

// Convention Java identifier
def res2 = 'a123b456_c' =~ /^(?!\d)([$\w]+?)(\d*)$/
print("${res2[0][1]} : ${res2[0][2]}") // => a123b456_c :

关于java - Java 标识符的正则表达式优化。将结尾的数字与其他部分分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45274934/

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