Separate content from a room via Regex

1

In 2 variables I want to perform the following operations. In the 1st, var chat1 , separate via regex 4 information: " A: ", " How are you? ", " B: " and " I'm fine, thanks. ", and be able to access them through their indexes using the capture groups. And in the 2nd, var chat2 , separate 2 information: " A: " and " How are you? ". I understand little regex and I did not get the results expected.

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:", "" ]
    
asked by anonymous 17.01.2018 / 02:00

2 answers

3

You can use in a simpler way, without ? , $ or \b :

(A:)(.*)(B:)(.*)

When you use ? in the last group, you must use $ so that it knows the end of the string. Therefore, it becomes unnecessary if you only use .* that will capture the whole string to the end of the line.

var chat1 = "A:How are you?B:I'm fine, thanks.";
var chat2 = "A:How are you?";

var c1 = chat1.match(/(A:)(.*)(B:)(.*)/i);
var c2 = chat2.match(/(A:)(.*)/i);
console.log(c1);
console.log(c2);
    
17.01.2018 / 04:02
0

Just add the $ character at the end of the expressions.

var chat1 = "A:How are you?B:I'm fine, thanks.";
var regex = /\b(A:)(.*?)(B:)(.*?)$/i;
var resultado = chat1.match(regex);
console.log(resultado);

var chat2 = "A:How are you?";
var regex = /\b(A:)(.*?)$/i;
var resultado = chat2.match(regex);
console.log(resultado);

Recommended reading:

17.01.2018 / 03:07