Ruby正则表达式,用于字母和数字或字母后跟句点、字母和数字

Ruby正则表达式,用于字母和数字或字母后跟句点、字母和数字,ruby,regex,Ruby,Regex,我正在尝试构造一个Ruby正则表达式,它只允许以下内容: some string (read letter only characters) some string followed by numbers some string followed by a period and another string some string followed by a period and another string followed by numbers period is only allowed

我正在尝试构造一个Ruby正则表达式,它只允许以下内容:

some string (read letter only characters)
some string followed by numbers
some string followed by a period and another string
some string followed by a period and another string followed by numbers
period is only allowed if another string follows it
no other periods are allowed afterwards
numbers may only be at the very end
/\A[A-Z]\w*(\.[A-Z]\w*)*\Z/i
我有
\A[^0-9.]A-z]*([0-9]*)([0-9]A-z]*)[0-9]*)\z
但我不能得到我需要的东西。这允许:

test.
test..
test.123
什么是正确的正则表达式?如果有人能解释我做错了什么,帮助我了解未来,那也太好了

编辑:更新需求,使其更具描述性

您可以尝试

^[a-z]+\.?[a-z]+[0-9]*$
这是

注意:使用
\A
\z
匹配字符串的开头和结尾,而不是行


您需要转义匹配任何单个字符的

模式说明:

  ^                        the beginning of the line
  [a-z]+                   any character of: 'a' to 'z' (1 or more times)
  \.?                      '.' (optional)
  [a-z]+                   any character of: 'a' to 'z' (1 or more times)
  [0-9]*                   any character of: '0' to '9' (0 or more times)
  $                        the end of the line
所以我猜您想要
标识符
分隔

通过
标识符
我的意思是:

  • 由字母数字字符组成的字符串
  • 这不是以数字开头的
  • 至少有一个字符长
作为语法写出来,它看起来像这样:

EXPR  := IDENT "." EXPR | IDENT
IDENT := [A-Z]\w*
EXPR  := IDENT [0-9]*
IDENT := STR | STR "." STR
STR   := [A-Z]+
这方面的正则表达式如下所示:

some string (read letter only characters)
some string followed by numbers
some string followed by a period and another string
some string followed by a period and another string followed by numbers
period is only allowed if another string follows it
no other periods are allowed afterwards
numbers may only be at the very end
/\A[A-Z]\w*(\.[A-Z]\w*)*\Z/i
试试看

注意:由于
\w
的行为,此模式也将接受第一个字符后的
\uu
(下划线)(即
测试123
也将通过)

编辑以反映问题的更新

所以你想要的语法实际上是这样的:

EXPR  := IDENT "." EXPR | IDENT
IDENT := [A-Z]\w*
EXPR  := IDENT [0-9]*
IDENT := STR | STR "." STR
STR   := [A-Z]+
那么regexp是这样的:

/\A[A-Z]+(\.[A-Z]+)?[0-9]*\z/i
试试这个

解释如下:

/            # start Regexp
  \A         # start of string
  [A-Z]+     # "some string"
  (          
    \.       # followed by a period
    [A-Z]+   # and another string
  )?         # period + another string is optional
  [0-9]*     # optional digits at the end
  \z         # end of string
/i           # this regexp is case insensitive.

解释你想通过什么和不通过什么。是否确实希望正则表达式只匹配列出的四个字符串?test.test.test123是否有效?
test123test
有效吗?等等。。不清楚你想要什么公平地说。。。如果他们能清楚地指定他们想要什么,他们可能就不需要问这个问题。
^
$
是一行的开头和结尾,而不是字符串。是的,我尝试了
\a
\z
但为什么它在演示中不起作用。我不知道ruby正则表达式模式。请你解释一下。因为你的输入中有多行,每一行都是一个测试用例。如果您使用
\A
\z
,那么它将尝试将所有测试用例作为模式的一个实例进行匹配,但它们不是(模式不允许换行符或任何空格)。但我的意思是,在你的解释中,你把
^
$
称为字符串的开头和结尾,当它们是一行的开头和结尾时。谢谢,我知道了。我把所有的单词放在演示的新行中,这就是为什么它不起作用。再次感谢。让我更新我的帖子。太好了,谢谢。我想我的正则表达式太复杂了!很高兴看到我想做什么,并解释为什么,这样我就可以为将来学习。