Regex: How to match last ocurrence, capture output as 2 groups?

Hi, regex question:

How can I capture the following groups using the same regex?

Example A:

Input:
something-E123

Output:
Capture group to Variables:
Variable 1: something
Variable 2: E123

⠀⠀⠀⠀⠀⠀

Example B:

Input:
some-text-EABC

Output:
Capture group to Variables:
Variable 1: some-text
Variable 2: EABC
⠀⠀⠀⠀⠀⠀

Example C:

Input:
something-something-moretext-EA1A

Output:
Capture group to Variables:
Variable 1: something-something
Variable 2: EA1A

Note: If it helps, the last 4 characters are always "EXXX", where XXX are four characters from A-Z or 0-9

Previously had been using this Regex:
([^=]*)-([^=]*)
It works for Example A, when there is only one - hyphen character, but doesn't work on Examples B or C when there's two or more hyphens present.

Thanks

This should work:
(?m)^(.+?)-(\w+)$

For RegEx details, see https://regex101.com/r/CXTF1U/1

Use a Search using Regular Expression action

If all of your examples are in one text string, then you will need to use a For Each action with a Substrings In collection.

1 Like

Unless practicing regular expressions is a higher priority than capturing the final string, it might be simpler to split on hyphens and take the last value from the resulting list.

If you did that in JS for example, perhaps:

Expand disclosure triangle to view JS Source
(() => {
    "use strict";

    const main = () => {
        const
            s = Application("Keyboard Maestro Engine")
            .getvariable("someHyphenatedString");

        // Split on all hyphens
        const xs = s.split("-");

        return last(xs);
    };

    // --------------------- GENERIC ---------------------

    // last :: [a] -> a
    const last = xs =>
        // The last item of a list.
        0 < xs.length ? (
            xs.slice(-1)[0]
        ) : null;

    return main();
})();

or in AppleScript:

Expand disclosure triangle to view AppleScript
--------------------------- TEST -------------------------
on run
	tell application "Keyboard Maestro Engine"
		set s to getvariable "someHyphenatedString"
	end tell
	
	set xs to splitOn("-", s)
	
	last item of xs
end run


------------------------- GENERIC ------------------------

-- splitOn :: String -> String -> [String]
on splitOn(needle, haystack)
	set {dlm, my text item delimiters} to ¬
		{my text item delimiters, needle}
	set xs to text items of haystack
	set my text item delimiters to dlm
	return xs
end splitOn

last matching segment.kmmacros (3.3 KB)

1 Like

Excellent, works as expected!
thank you JM and CP! appreciate the quick response.