简体   繁体   中英

Regular expression for match string with new line char

How use regular expression to match in text passphrase between Passphrase= string and \\n char (Select: testpasssword )? The password can contain any characters.

My partial solution: Passphrase.*(?=\\\\nName) => Passphrase=testpasssword

[wifi_d0b5c2bc1d37_7078706c617967726f756e64_managed_psk]\nPassphrase=testpasssword\nName=pxplayground\nSSID=9079706c697967726f759e69\nFrequency=2462\nFavorite=true\nAutoConnect=true\nModified=2018-06-18T09:06:26.425176Z\nIPv4.method=dhcp\nIPv4.DHCP.LastAddress=0.0.0.0\nIPv6.method=auto\nIPv6.privacy=disabled\n

The only thing you were missing is the the lazy quantifier telling your regex to only match as much as necessary and a positive lookbehind. The first one being a simple question mark after the plus, the second one just prefacing the phrase you want to match but not include by inputting ?<= . Check the code example to see it in action.

(?<=Passphrase=).+?(?=\\n)

 const regex = /(?<=Passphrase=).+?(?=\\\\n)/gm; const str = `[wifi_d0b5c2bc1d37_7078706c617967726f756e64_managed_psk]\\\\nPassphrase=testpasssword\\\\nName=pxplayground\\\\nSSID=9079706c697967726f759e69\\\\nFrequency=2462\\\\nFavorite=true\\\\nAutoConnect=true\\\\nModified=2018-06-18T09:06:26.425176Z\\\\nIPv4.method=dhcp\\\\nIPv4.DHCP.LastAddress=0.0.0.0\\\\nIPv6.method=auto\\\\nIPv6.privacy=disabled\\\\n `; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); } 

With QRegularExpression that supports PCRE regex syntax, you may use

QString str = "your_string";
QRegularExpression rx(R"(Passphrase=\K.+?(?=\\n))");
qDebug() << rx.match(str).captured(0);

See the regex demo

The R"(Passphrase=\\K.+?(?=\\\\n))" is a raw string literal defining a Passphrase=\\K.+?(?=\\\\n) regex pattern. It matches Passphrase= and then drops the matched text with the match reset operator \\K and then matches 1 or more chars, as few as possible, up to the first \\ char followed with n letter.

You may use a capturing group approach that looks simpler though:

QRegularExpression rx(R"(Passphrase=(.+?)\\n)");
qDebug() << rx.match(str).captured(1);   // Here, grab Group 1 value!

See this regex demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM