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

标签 java regex groovy

我需要读取一个字符串作为有效的 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/

相关文章:

java - Groovy(或 Java)中 sortedset 的子集

grails - 如何在Grails Controller 中调用方法而不渲染新 View ?

java - 如何避免两个类之间的循环依赖?

java - 为什么 onCreate 被重写?

java - BorderLayout 区域中的多个对象

python - 为什么 Python 正则表达式 ".*PATTERN*"匹配 "XXPATTERXX"?

python - 检查文本文件中是否存在字符串

java - Eclipse 最近的文件

c# - 强密码的正则表达式

grails - 如何将对象实例从一个 Controller 传递到grails中的另一个 Controller 中的 Action