RegEx:获取每个单词,直到最后4个单词

时间:2015-12-10 09:05:05

标签: regex regular-language

我有像

这样的字符串
  1. wwww-www-ww-ww
  2. w
  3. 许多-wwww-wwww分开 但它不是常规w-w-w-w,也可能是wwww-wwww

    我试图找到一个正则表达式,捕获每个单词,直到最后4个单词 因此,示例1的结果将是第一个8w(wwww-w
    对于第二个例子,前5w(^\w*(?=\w{4}$)

    是否可以在正则表达式中执行此操作? 我现在有这样的事情:

    [^-]*(?=\w{4}$)
    

    或者

    -

    我的“解决方案”有两个问题:

    1. 最后4个单词不会被捕获,例如2.它们被-

    2. 打断
    3. 不会捕获最后4个字之前的字词。它们被xhr.send(JSON.stringify(jsonData))打断。

1 个答案:

答案 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

测试live on regex101.com