const regex = /\[\ (RUNNING|STOPPED)\ \]
(.+?)
(?:\[Pid:\ (\d+)\]|$)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('\\[\\ (RUNNING|STOPPED)\\ \\]
(.+?)
(?:\\[Pid:\\ (\\d+)\\]|$)', 'gm')
const str = `
I want to extract the words between the two bracket "blocks" and also the word in first brackets (RUNNING or STOPPED).
Example (extract the bolded part):
[ RUNNING ] My First Application [Pid: 4194]
[ RUNNING ] Second app (some data) [Pid: 5248]
[ STOPPED ] Logger App
So, as you can see, the [Pid: X] part is optional. I can write the regex as follows:
\\[\\s+(RUNNING|STOPPED)\\s+\\]\\s+([^\\[]+).*
and it will work. But this would fail if App name would contain the '[' character. I tried the following, but it won't work:
\\[\\s+(RUNNING|STOPPED)\\s+\\]\\s+(?!\\[Pid)+.*
My idea was to match any words/characters that are not starting with "[Pid", but I guess this would match any words that are not followed by "[Pid".
Is there any way to do exactly that: Match any word that is not "[Pid", i.e. match the part until first appearing of "[Pid" substring?
`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
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}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions