1
In 2 variables I want to perform the following operations. In the 1st, var chat1
, separate via regex 4 information: "To:", "How are you?", "B:" and "I’m fine, Thanks.", and be able to access them by their contents using the capture groups. And in the 2nd, var chat2
, separate 2 pieces of information: "To:" and "How are you?". I understand little of regex and ended up not getting the expected results.
var chat1 = "A:How are you?B:I'm fine, thanks.";
var chat2 = "A:How are you?";
var c1 = chat1.match(/\b(A:)(.*?)(B:)(.*?)\b/i);
// c1[1] daria "A:", c1[2] daria "How are you?", c1[3] daria "B:" e c1[4] daria "I'm fine, thanks."
var c2 = chat2.match(/\b(A:)(.*?)\b/i);
// c2[1] daria "A:", c2[2] daria "How are you?"
console.log(c1);
// Resultado:
Array [ "A:How are you?B:", "A:", "How are you?", "B:", "" ]
console.log(c2);
// Resultado:
Array [ "A:", "A:", "" ]
Is there any way to get the exact expression and nothing else? Ex: if
var c1
werechat2.match(/(A:)(.*)/i)
would not marry, and vice versa, ifvar c2
werechat1.match(/(A:)(.*)(B:)(.*)/i)
nor would you marry.– eden
In the original the variables
chat1
andchat2
are actually a single variable (var chat
), which can contain both values. What happens is that the expression.match(/(A:)(.*)/i)
, when applied to the variablechat1
also returns true, including B:I’m fine, Thanks. (the answer), undesirable. What I would like is that expression.match(/(A:)(.*)/i)
only relate if the expression were only "A:How are you?" (the question) and not "A:How are you? B:I’m fine, Thanks." (the question and the answer).– eden
Did not work. The result gives null for both expressions.
– eden
@Eden If the
A:
will always end in?
(for always a question), this may help https://jsfiddle.net/o19n8824/2/ (I took the/i
, I don’t know if it’s necessary)– Sam
1º I need to keep the capture groups the way they are so I can use them individually later;
(A:)
separate from(.*)
and not along the way you put it:(A:.*)
. 2º I don’t want you to regex her.match(/(A:)(.*)/i)
extracts the part of the question, and yes that gives true marry the whole expression (A:How are you?) and false/null if it also contains the part of the reply.– eden
@Eden When executing the snippet, see that the array returns the separate values. You can use them by taking the index.
– Sam