gpt4 book ai didi

ruby 正则表达式 : split string with match beginning with either a newline or the start of the string?

转载 作者:太空宇宙 更新时间:2023-11-03 16:08:55 25 4
gpt4 key购买 nike

这是我为此准备的正则表达式。我使用 Ruby,如果我没记错的话,它使用 POSIX 正则表达式。

regex = /(?:\n^)(\*[\w+ ?]+\*)\n/

这是我的目标:我想用正则表达式拆分一个字符串,该正则表达式是 *delimited by asterisks*,包括那些星号。 但是:如果匹配以换行符 (\n) 开头,或者它是整个字符串的开头,我只想按匹配拆分。这是我正在使用的字符串。

"*Friday*\nDo not *break here*\n*But break here*\nBut again, not this"

我的正则表达式在 *Friday* 匹配时没有正确拆分,但它*But break here* 匹配时拆分(它也在 here split 中抛出)。我的问题在第一组的某处,我认为:(?:\n^) — 我知道这是错误的,但我不完全确定正确的编写方式。有人可以阐明一下吗?这是我的完整代码。

regex = /(?:\n^)(\*[\w+ ?]+\*)\n/
str = "*Friday*\nDo not *break here*\n*But break here*\nBut again, not this"
str.split(regex)

结果是:

>>> ["*Friday*\nDo not *break here*", "*But break here*", "But again, not this"]

我希望它是这样的:

>>> ["*Friday*", "Do not *break here*", "*But break here*", "But again, not this"]

编辑#1:我更新了我的正则表达式和结果。 (2011/10/18 16:26 CST)
编辑#2:我再次更新了这两个。 (中部标准时间 16:32)

最佳答案

如果你只是在每个字符串的前面添加一个'\n'会怎么样。这大大简化了处理过程:

regex = /(?:\n)(\*[\w+ ?]+\*)\n/
str = "*Friday*\nDo not *break here*\n*But break here*\nBut again, not this"

res = ("\n"+str).split(regex)
res.shift if res[0] == ""
res
=> [ "*Friday*", "Do not *break here*",
"*But break here*", "But again, not this"]

我们必须关注最初的加时赛,但还算不错。我怀疑有人可以将其缩短一点。

关于 ruby 正则表达式 : split string with match beginning with either a newline or the start of the string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7813801/

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