Marek
Marek

Reputation: 147

php Regex file path | second matching after specific character

I trying to extract file patches, without disk letter, that are inside text. Like from AvastSecureBrowserElevationService; C:\Program Files (x86)\AVAST Software\Browser\Application\elevation_service.exe [X] extract :\Program Files (x86)\AVAST Software\Browser\Application\elevation_service.exe.

My actual regex look like this, but it will stop on any space, which can contains file names.

(?<=:\\)([^ ]*)

The soulution that I figure out is, that I can match first space character after dot, because there is very little chance that there will be some directory name with space after dot, and I will always do fast manual check. But I do not know how to write this in regex

Upvotes: 2

Views: 143

Answers (3)

Junitar
Junitar

Reputation: 999

You can use the following regex:

[A-Z]\K:.+\.\w+

It will match any capital letter followed by :, then any character string ending wit ., followed by at least one word character.

\K removes from the match what comes before it.

Demo

Upvotes: 0

Emma
Emma

Reputation: 27763

Here we would consume our entire string, as we collect what we wish to output, and we would preg_replace:

.+C(:\\.+\..+?)\s.+

Test

$re = '/.+C(:\\.+\..+?)\s.+/m';
$str = 'AvastSecureBrowserElevationService; C:\\Program Files (x86)\\AVAST Software\\Browser\\Application\\elevation_service.exe [X]';
$subst = '$1';

$result = preg_replace($re, $subst, $str);

echo $result;

Demo

Upvotes: 1

anubhava
anubhava

Reputation: 786359

You may use this regex for this purpose:

(?<=[a-zA-Z]):[^.]+\.\S+

RegEx Demo

RegEx Details:

  • (?<=[a-zA-Z]): Lookbehind to assert we have a English letter before :
  • :: Match literal :
  • [^.]+: Match 1+ non-dot characters
  • \.: Match literal .
  • \S+: Match 1+ non-whitespace characters

Upvotes: 2

Related Questions