I am trying to split a string into an array of words that is present within [] as the limiters. Text within [] should be only considered. Consider a string being =>
const stringA = '[@Mary James], [@Jennifer John] and [@Johnny Lever[@Patricia Robert] are present in the meeting and [@Jerry[@Jeffery Roger] is absent.'
Now I want to break the string into an array that will only contain the string within [].
const stringB = ['Mary James', 'Jennifer John', 'Patricia Robert', 'Jeffery Roger'];
Any logic can be applied to be able to the needed resolution.
On searching found a regex =>
stringA.match(/(?<=\[@)[^\]]*(?=\])/g);
But the above doesn't fullfill my requirement.
The above regex gives me
const wrong = ['Mary James', 'Jennifer John', 'Johnny Lever[@Patricia Robert', 'Jerry[@Jeffery Roger'];
The required array doesn't match to the recieved array from the above regex.
CodePudding user response:
Close, just missing the exclusion of [
:
stringA.match(/(?<=\[@)[^\[\]]*(?=\])/g);
// ^^ exclude '[' as well as ']'
CodePudding user response:
The OP's regex does not feature the opening bracket within the negated character class, thus changing the OP's /(?<=\[@)[^\]]*(?=\])/g
to (?<=\[@)[^\[\]]*(?=\])
already solves the OP's problem for most environments not including safari browsers due to the lookbehind which is not supported.
Solution based on a regex ... /\[@(?<content>[^\[\]] )\]/g
... with a named capture group ...
const sampleText = '[@Mary James], [@Jennifer John] and [@Johnny Lever[@Patricia Robert] are present in the meeting and [@Jerry[@Jeffery Roger] is absent.'
// see ... [https://regex101.com/r/v234aT/1]
const regXCapture = /\[@(?<content>[^\[\]] )\]/g;
console.log(
Array.from(
sampleText.matchAll(regXCapture)
).map(
({ groups: { content } }) => content
)
);