Regex match overlap/crossover

后端 未结 1 1798
野趣味
野趣味 2021-01-23 04:32

I need to capitalise acronyms in some text.

I currently have this regex to match on the acronyms:

/(^|[^a-z0-9])(ECU|HVAC|ABS|ESC|EGR|ADAS|HEV|HMI)($|[^a         


        
相关标签:
1条回答
  • 2021-01-23 05:28

    Yes the reason is because it overlaps (when matching the abs, it also consumes the /. Then for esc, it cannot find [^a-z0-9] because the next letter it is scanning is e).

    You could use this RegEx instead:

    \b(ECU|HVAC|ABS|ESC|EGR|ADAS|HEV|HMI)\b
    

    \b is a Word Boundary, it does not consume any characters and therefore there will be no overlap

    Live Demo on Regex101


    You can also change your RegEx to use a Positive Lookahead, since this also does not consume characters:

    (^|[^a-z0-9])(ECU|HVAC|ABS|ESC|EGR|ADAS|HEV|HMI)(?=$|[^a-z0-9])
    

    Live Demo on Regex101

    0 讨论(0)
提交回复
热议问题