gpt4 book ai didi

java - 解析一串由空格分隔、有序但可选的元素

转载 作者:行者123 更新时间:2023-11-30 07:36:16 26 4
gpt4 key购买 nike

这是对我要解决的特定问题的概括。

给定一串由单个空格分隔的唯一可识别元素:

0 1 2 3 4

在不修改字符串的情况下,当任意数字为非1且数字有序时,用什么正则表达式匹配该表达式?

其他有效字符串的例子:

2
0 4
1 4
0 1 2 3
0 1 3 4
0 1 2 3 4

最佳答案

正则表达式可能不是最好的工具。如果您可以使用前瞻,那么对于您给出的示例来说,这几乎是可管理的:

^(?=0? ?1? ?2? ?3? ?4?$)(?:\d )*\d$

Rubular

解释:

^                       Match the start of line/string.(?=0? ?1? ?2? ?3? ?4?$) Look ahead to restrict to 0 to 4 in that order.(?:\d )*\d              Ensure that the string is alternating digit then space.$                       Match the end of line/string.

To generalize it to fixed length strings all of equal length makes it slightly more difficult to read. For example for ab ba cd de ef it will look like this:

^(?=(?:ab)? ?(?:ba)? ?(?:cd)? ?(?:de)? ?(?:ef)?$)(?:\w{2} )*\w{2}$

Rubular


但是将它推广到不同长度的单词会变得更加困惑,例如对于 zero one two three 4 你可以使用这个正则表达式:

^(?=(?:zero)? ?(?:one)? ?(?:two)? ?(?:three)? ?(?:four)?$)(?! )(?: ?(?:zero|one|two|three|four)(?= |$))+$

Rubular

关于java - 解析一串由空格分隔、有序但可选的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3696848/

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