javascript - 正则表达式匹配多个可能的选项

标签 javascript regex

我无法为我遇到的这个问题给出正确的标题,但我正在尝试找出如何编写一个正则表达式,该正则表达式能够匹配下面列表中的几个可能的选项。

Describe what rules should regex consider as valid?

  • 必须以 dfr 开头
  • 在其开头的关键字后必须包含一个破折号 -
  • 可以包含双破折号--,如果它继续使用以下关键字之一:baserootx , y
  • 如果包含双破折号+关键字,例如dfr--base 后面必须包含另一个破折号,例如dfr--base-
  • 之后它只能包含字母,它应该只验证小写和驼峰式大小写。
  • 应使用单破折号 - 链接,并在后面包含字母

To clarify with some examples, those should be valid:

dfr--base-color-dark
dfr--root-size
dfr--x-spacing
dfr-spacing
dfr-fontWeight
dfr-borderRadius-extraSmall
dfr-grid-columns

I think that I'm very bad with regex, but of course I spent some time trying to figure this out... Playing around with RegExr.com

^dfr-((-?(base|root|x|y)+([a-zA-Z-])+)$|([a-zA-Z-]+)$)

它似乎有效,但我不确定这是否足够好,是否有一些失败案例等等......

我试图尝试一些不应该有效的例子,但它似乎很糟糕......

dfra // good
dfra- // good
dfr-Q // good
qwe-asd // good
dfr--asd // good
dfr-as2dqw // good
dfr--base--dog // good
dfr--root--x // fails (it should not pass with double dash of two keywords)
dfr-x1223 // good

感谢任何帮助。我在这里苦苦挣扎💣!

更新#1:

我刚刚更新了我的正则表达式,它似乎更好了,但还不太确定。

更新#2:

以下是它应该能够验证什么和不应该验证什么的一些示例:

// Should pass
dfr-borderRadius-extraSmall
dfr-borderRadius-full
dfr--base-color-dark
dfr--root-fontSize-small
dfr--base-fontSize
dfr-borderWidth

// Should fail
not-dfr
not-dfr-asd
dfr-1
dfr-@
dfr--a
dfr--base
dfr-root-
dfr--x-1
dfr--root--x
dfr--root-Something
dfr-border--x
dfr-asd-Asd

最佳答案

你可以用这个模式来做到这一点:

^dfr(?:--(?:base|root|[xy]))?(?:-(?!base\b|root\b|[xy]\b)[a-z]+(?:[A-Z][a-z]+)*)+$

demo

详情:

^dfr
(?:--(?:base|root|[xy]))? # optional keyword

(?: # group for other parts
    -
    (?!base\b|root\b|[xy]\b) # negative lookahead (not followed by a keyword)
    [a-z]+(?:[A-Z][a-z]+)* # a camelCase word
)+ # repeat one or more times
$

请注意,单词边界足以检查单词后面是否有破折号或字符串结尾,因为字符串中只允许使用字母和破折号。

关于javascript - 正则表达式匹配多个可能的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50709329/

相关文章:

javascript - IE 6/7 Access Denied trying to access a popup window.document

javascript - 使用 javascript/jquery 自动滚动到固定点

ruby - 如何获取数字之间的特定点

c++ - 将读取行与正则表达式进行比较

javascript - 似乎无法为特定情况制作正则表达式

python - 如何从 Pandas 的地址中提取公寓

javascript - 如何在 JavaScript 中显示 "take variables out of an object"

javascript - 优化从另一个数组对一个数组进行排序

javascript - 声明内联样式与类时的行为变化

regex - 如何自动排除/删除 import.io 字段中的文本提取