I’m having a requirement of js regex should return the object from String.
String: 'A: 100 - 200, B: Test & Test2, Tes3, C: 40, D: 11 22, E: E 444,55E'
Output:
{
A: '100 - 200',
B: 'Test & Test2, Tes3',
C: '40',
D: '11 22',
E: 'E 444,55E'
}
I tried with following regex.
const regexp = /([^:]+): ?([^,]*),? ?/g;
But the output was not correct. Value for E is wrong.
{A: '100 - 200', B: 'Test & Test2', Tes3C: '40', D: '11 22', E: 'E 444'}
4
Answers
You could split the string and get parts for the object.
You could use some lookahead:
Open in the playground
Similar to other answers, in one functional expression:
If speed is important, then use the traditional
exec
method:The regex that you tried
([^:]+): ?([^,]*),? ?
also has a matchTes3, C: 40
which is not correct besides the match for E.You get those matches because this part
[^,]*
does not match a comma, so it will stop when it encounters the first one.Also note that when using a pattern like this with negated character classes
([^:]+): ?([^,]*)
it can also match just:
Another version with 2 capture groups:
The regex in parts match:
b
A word boundary to prevent a partial word match([A-Z]+)
Capture group 1, match 1+ chars A-Z:s+
Match a colon and 1+ whitespace chars(
Capture group 2[^s,][^,]*
Match at least 1 non whitespace char other than a comma followed by 0+ chars other than a comma(?:
Non capture group to repeat as a whole,(?!s+[A-Z]+:)
Match a comma when not directly followed by whitespace chars, 1+ chars A-Z and a colon[^,]*
Match optional characters other than a comma)*
Close the non capture group and optionally repeat it)
Close group 2See a regex demo