Regex to find last occurrence of pattern in a string

前端 未结 4 1274
一个人的身影
一个人的身影 2021-01-14 00:02

My string being of the form:

\"as.asd.sd fdsfs. dfsd  d.sdfsd. sdfsdf sd   .COM\"

I only want to match against the last segment of whitespa

4条回答
  •  無奈伤痛
    2021-01-14 00:45

    In a general case, you can match the last occurrence of any pattern using the following scheme:

    pattern(?![\s\S]*pattern)
    (?s)pattern(?!.*pattern)
    pattern(?!(?s:.*)pattern)
    

    where [\s\S]* matches any zero or more chars as many as possible. (?s) and (?s:.) can be used with regex engines that support these constructs so as to use . to match any chars.

    In this case, rather than \s+(?![\s\S]*\s), you may use

    \s+(?!\S*\s)
    

    See the regex demo. Note the \s and \S are inverse classes, thus, it makes no sense using [\s\S]* here, \S* is enough.

    Details:

    • \s+ - one or more whitespace chars
    • (?!\S*\s) - that are not immediately followed with any 0 or more non-whitespace chars and then a whitespace.

提交回复
热议问题