Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

php - Regex match overlap/crossover

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-z0-9])/ig

Explanation: this is aiming to match any of the acronyms where they are either at the start or end of the text, or there isn't a letter or number either side of them (as then they might be part of a word - e.g. I wouldn't want to replace the "Esc" in the word "Escape").

This works most of the time, but doesn't work for the following example:

"abs/esc"

It matches the abs, but not the esc. I'm guessing this is because the matches overlap, in that the forward slash is part of the match relating to abs.

Can anyone suggest how to get a match on both?

As a side note, I'm using PHPs preg_replace_callback to perform the transformation afterwards:

$name = 'abs/esc';
$name = preg_replace_callback('/(^|[^a-z0-9])('ECU|HVAC|ABS|ESC|EGR|ADAS|HEV|HMI')($|[^a-z0-9])/i', function($matches) {
    return $matches[1] . strtoupper($matches[2]) . $matches[3];
}, $name);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...