I'm trying to create a regex expression that has has multiple conditions separated by | (OR). I want to use capture groups but I'm not getting it to work fully.
3 sample strings:
--- {source-charset: '', encoding-error-limit: '', class: stat-direct, directory: \\\myserver\C\FOLDER\SUB_FOLDER}
--- {odbc-connect-string-extras: '', server: hello.sample.com, dbname: X_DB, port: '80', class: hello, username: USERX}
--- {cleaning: 'no', filename: //myserver/D/FOLDER/SUB_FOLDER/File name.xlsx, dataRefreshTime: '', interpretationMode: '0'}
For each sample string I would like the regex to return:
\\\myserver\C\FOLDER\SUB_FOLDER
X_DB
//myserver/D/FOLDER/SUB_FOLDER/File name.xlsx
Basically the value after either directory:, dbname: or filename: and ending with } for one of them and , for two.
I've managed to use OR statements to get the three conditions in. regex extract
'directory: [^}]+|dbname: [^,]+|filename: [^,]+'
That returns:
directory: \\\myserver\C\FOLDER\SUB_FOLDER}
dbname: X__DB,
filename: //myserver/D/FOLDER/SUB_FOLDER/File name.xlsx,
If I introduce capturing groups I only get the right return for one of the parts: 'directory: ([^}]+)|dbname: ([^,]+)|filename: ([^,]+)'
That returns:
\\\myserver\C\FOLDER\SUB_FOLDER
null
null
I've managed to get it working with a nested regex that takes the result from
'directory: [^}]+|dbname: [^,]+|filename: [^,]+'
and uses:
': ([^,}]+)'
That gives me the result I want but I would like to do this as one regex. Any help would be greatly appreciated.
/Aron
You could use a negated character class to match not a {, } or a comma, match any of the options in a non capturing group and use and a single capturing group the capture the values:
{[^{]+(?:filename|directory|dbname): ([^,}]+)[^}]*}
Explanation
{ Match {[^{]+ Match 1+ times not { using a negated character class(?:filename|directory|dbname): Match any of the listed options followed by : and a space( Capture group1
[^,}]+ Match 1+ times not , or }) Close group 1[^}]*} Match 0+ times not }, then match }Regex demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With