我正在寻找使用正则表达式拆分字符串(并获取所有匹配项)。
我有以下字符串:
ppc.goo.gen.heat..jan-17.logo
它应该返回每个之间的一切。
[0] ppc
[1] goo
[2] gen
[3] heat
[4]
[5] jan-17
[6] logo
到目前为止我有这个:
([a-zA-Z0-9-]*)\.
哪个匹配0到5,但它将错过匹配6,因为它没有。 最后。 我尝试使用lookahead,但我无法使用它。 有小费吗?
I'm looking to split a string (and get all the matches) using a regular expression.
I have the following string:
ppc.goo.gen.heat..jan-17.logo
It should return everything between each .
[0] ppc
[1] goo
[2] gen
[3] heat
[4]
[5] jan-17
[6] logo
So far I have this:
([a-zA-Z0-9-]*)\.
Which matches 0 to 5, but it'll miss off match 6 as it doesn't have a . at the end. I tried using lookahead but I couldn't get it working. Any tips?
原文:https://stackoverflow.com/questions/42269148
更新时间:2022-03-09 10:03
最满意答案
第1组将成为参赛作品。
(?:^|\.)
匹配字符串的开头,或.
([^\.]*)
匹配0或更多非.
人物(?=\.|$)
匹配.
或者字符串的结尾
Group 1 will be the entry.
(?:^|\.)
Match start of string, or.
([^\.]*)
Match 0 or more non-.
characters(?=\.|$)
Match.
or end of string
我有一个正则表达式,旨在匹配特定语法,n次,每次出现后都有一个管道(|),除了最后一次出现。目前,我的模式是沿着(pattern)\|{3}
的路线,但是这不符合没有尾随管道的要求。无论如何,我可以完成这个没有重复(pattern)
?我能想到的最佳解决方案是(pattern)\|{2}(pattern)
。正则表达式:重复模式n次,最终重复的变化
有效实施例:
* | 401 | [2-10]
无效实施例:
* | 401 | [2-10] |
的(pattern)
值是无关的回答我的具体问题,但为了完整起见,在这里它是在其目前的形式:(?:(?:((\*)|(\[[\w+ ]\-[\w+ ]\])|(\d+)))\|){3}
编辑
这是正在内.NET消耗, JavaScript的。
2014-12-19 Nathan Taylor
+0
你能提供一个真实的例子吗? – 2014-12-19 01:01:45
+0
同样,我不认为这对于实际问题来说是非常关键的,但是这将是一个有效输入的例子:'[1-2] | * | 254' – 2014-12-19 01:03:03
+0
'我能想到的最好的解决方案是)\ | {2}(pattern)。“在我看来,这是最好的解决方案 - 您不必关心处理不匹配的模式和分隔符的数量。为了防止重复,只需使用字符串连接来构建模式。 – nhahtdh 2014-12-19 02:17:34
A
回答
4
有一个简单的解决方案,如果你匹配整个输入字符串:
(?:pattern(?:\|(?!$)|$)){3}
这意味着:符合模式依次为:
- 要么
\|(?!$)
:管道不是后面跟着字符串的尾部 - 或
$
字符串的末尾
3次。
针对您的特殊模式,这将是:
^(?:(?:((\*)|(\[[\w+ ]\-[\w+ ]\])|(\d+)))(?:\|(?!$)|$)){3}
我也为前缀的图案^
,因为如果你在整个输入反正匹配此解决方案才有效。