我有像
这样的字符串wwww-www-ww-ww
w
许多-
与wwww-wwww
分开
但它不是常规w-w-w-w
,也可能是wwww-wwww
我试图找到一个正则表达式,捕获每个单词,直到最后4个单词
因此,示例1的结果将是第一个8w(wwww-w
)
对于第二个例子,前5w(^\w*(?=\w{4}$)
)
是否可以在正则表达式中执行此操作? 我现在有这样的事情:
[^-]*(?=\w{4}$)
或者
-
我的“解决方案”有两个问题:
最后4个单词不会被捕获,例如2.它们被-
不会捕获最后4个字之前的字词。它们被xhr.send(JSON.stringify(jsonData))
打断。
答案 0 :(得分:1)
是的,可能会有一个稍微复杂一点的先行断言:
/\w(?=(?:-*\w){4,}$)/x
<强>解释强>
/ # Start of regex
\w # Match a "word" character
(?= # only if the following can be matched afterwards:
(?: # (Start of capturing group)
-* # - zero or more separators
\w # - exactly one word character
){4,} # (End of capturing group), repeated 4 or more times.
$ # Then make sure we've reached the end of the string.
) # End of lookahead assertion/x