Regular Expression handling

This is the string I have saved into a variable...

Full Name: 可爸爸
Username: lgfee

I used https://regex101.com/ using

(?<=Name:).*$

returns 可爸爸

However when I use in Keyboard Maestro it's returning lgfee instead. I want to just grab whatever data comes after Full Name:

In regex101 you probably have set the m flag (multi line):

05-pty-fs8

55-pty-fs8

You have to set the m flag in KM too:

(?m)(?<=Name:).*$

If you don’t set it, $ will match the end of the string (not the end of the line).


Regex%20with%20%60m%60%20Flag%20%3C9381%20200223T193129%3E-pty-fs8
Regex with ‘m’ Flag <9381 200223T193129>.kmmacros (3.0 KB)

1 Like

Thanks for the help :slight_smile:

One final thing. In some cases not all cases there is a single whitespace after the :

is there anything to apply that can remove that whitespace only if it exists?

Sorry Tom last one. In some cases that full name field might be

John Smith Morgan

I would just want the first word John. How to get that, oh and my previous post about the whitespace after : being removed.

Sorry for being a pain :slight_smile:

I would do this:

(?m)Name: ?(.*$)

Regex%20with%20%60m%60%20Flag%20(part%20two)%20%3CAE24%20200223T203548%3E-pty-fs8 Search using Regular Expression <AE24 200223T203548>.kmactions (574 Bytes)

  • If there are possibly multiple whitespaces, then use * instad of ? after the space character
  • If different types of (horizontal) whitespaces are possible, then use \h instead of the ordinary space character

This, for example:

^\w+\b

Sorry for dumb quesiton but how would that look with the (?m)Name: ?(.*$) statement how would it sit within that?

John Smith Morgan

For instance with (?m)Name: ?(\w+\b.)

returns

Name: John

with whitespace. When what I need is

John

no whitespace either side, and getting the first name

I don’t get any whitespace. But you have added a period after the \b in your expression above. A period matches any character.

Without period:

(?m)Name: ?(\w+\b)

or just (I don’t know why I have added the \b at all):

(?m)Name: ?(\w+)

I recommend to use regex101 as a playground. In the side bar you find the explanation for every detail of the current expression:

thanks but I'm still getting

Name: John

As the result when I use (?m)Name: ?(\w+)

How to get just the John

Like in the action I uploaded for you in the post above:

Capture group 1 to the variable, not “all”. Group 1 is the stuff inside the parenthesis.


PS:

If I’m not sure how an action works I always open the Help, in the Gear menu of the action:

29-pty-fs8

This leads directly to the corresponding Wiki article. In this case this one.

Sorry my bad for missing that, works great thank-you very much for the help & lessons!