kairos kairos - 1 year ago 86
AppleScript Question

Extract substring from path. Make sure the extracted substring isn't followed by a character

Let's say I have this string:


I want to extract a substring that ends with a matching condition ("
") but that isn't followed by a specific character ("

The result should be:


Case 1

In the case of "
" before "
" followed by any other character or none:


The result should be:


Since the first "
" is followed by a "

Case 2

In case there are two matches:


The result should be:


I want to keep just the first substring.

Case 3

In the case there isn't any "
" without a following "


The result should be:


The regex should output "
" when there is no occurrences.

Case 4

In case there is a "
" followed by any other character besides "
" or "nothing more" :




The result should be:


Any ideas? Thanks!

NOTE: I want to use this regex in Applescript:

set strRegEx to ???
set strResult to find text strRegEx in strTextToSearch with regexp and string result

UPDATE: Added Case 4

Answer Source

Here is one solution:


Demo (Note: The ^ in this demo is only added to show multiple examples together; you shouldn't need it.)


. - matches any character

*? - repeats the previous pattern as many times as necessary, but at little as possible ("non-greedy").

match - literal text for the word "match"

(?!...) a negative lookahead; the contained pattern is not included in the result, and cannot be matched.

\. a literal "." (the \ prevents it from being treated as "any character", like above)


Taking into consideration the "case 4" that you've now added, you could perhaps change the regex to:




(?=...) is a positive lookahead.

\/ matches a literal "/" character.

$ matches the end of the line.

\/|$ matches either of the above.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download