Q: Extract application name from user agent I am using the following regex to extract application name from user agents:
^([^\s/\[]+)([\s/\[]|\z)
Application name termination character class consists of white space, backslash and [.
It reads any character that is not whitespace or / or [ until characters from the beginning until whitespace or / or [
link : https://regex101.com/r/7ndDEq/1
It is failing on some application name which has white space in between and extracts characters before white space.
eg:
Based on above regex on:
Pump Log/1300 CFNetwork/1121.2.2 Darwin/19.3.0

It extracts Pump
but the ground truth is Pump Log

A: Try this:
^([^\s/[]+(?:\s[\w]+/)?)

It's almost there (the last slash should be removed in some matches).
The principle is simple: after capturing the required string, allow the regex to catch the optional stuff (in our case it's the second word after the first space) as well if it is available after the main match (the ? sign at the end makes this second part like optional).
UPD: this one is more general
^([^\s/[]+(?: [^/\d]+)?)

But there are two interesting points here:

*

*I had to put a whitespace in regex, \s did not work there, I don't know how it will be in the code

*It is required to have some rule what is possible after the whitespace, where we need to stop in the second optional part. If it's a slash or a bracket that will work fine but in strings like Apple iPhone10,4 iOS v13.3.1 Main/3.2.0 or POF 12.51.1859; (iPhone8,4; iOS 13.3.1; en_US; g=ON; p=ON; r=WWAN) 56BA8A93-3748-4C5E-9D00-D811FCC4EBCE; it's hard to find where to stop...


A: Unless I'm misreading your requirements, your application name is anything up to but not including the first slash, which would just be
^([^/]+)

Or depending on your regex engine (which you should always specify when asking regex questions), you could do this with PCRE:
^(.+?)/


A: You might specify the allowed characters in a character class or use an alternation |
You can extend those to allow more characters or allowed strings.
^([^\s/\[]+(?: (?:& )?[A-Z][a-z]*)*)(?:[\s/\[]|\Z)


*

*^ Start of string

*( Capture group 1

*

*[^\s/\[]+ Match 1+ times any char except a whitespace char, / or [

*(?:  Match a space (Or use \s+ to match 1+ whitespace chars which could also match a newline)

*

*(?:& )?[A-Z][a-z]* Optionally match &  and  match an uppercase char A-Z followed by optional lowercase chars a-z



*)*  Close non capture group and optionally repeat



*) Close group 1

*(?:[\s/\[]|\Z) Match either a space / [ or assert the end of the string

Regex demo
Note that as you selected Python on regex101, you can use \Z to assert the position at the end of the string.
