Veda99817
Veda99817

Reputation: 169

Regex match string before and after a specific character

I would like to make a grouping to select the strings before AND after a specific character, in this case it's the Colon.

Example:

First: foo Last: bar

I would like to Match First and foo in group 1 and Last bar in group 2

Group1: First foo

Group2: Last bar


I currently have

([^:]*)+([^:*])

Which only matches everything that's not a colon, which isn't exactly what i'm looking for. What are some ways or patterns with regex where i can match before and after a certain character?

Upvotes: 0

Views: 10923

Answers (3)

Alexander Solonik
Alexander Solonik

Reputation: 10230

You can use the following regex:

([a-zA-Z]+:\s*[a-zA-Z]+) 

You can try it out on the link HERE.

'First: foo Last: bar'.match(/([a-zA-Z]+:\s*[a-zA-Z]+)/g) // ["First: foo", "Last: bar"]

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

The texts you want to get into single group is not a streak of continuous chars, thus, it is impossible to achieve. You need to grab the two parts, key and value separately, and then join them:

var rx = /([^:]+):\s*(.*?)(?=\w+:|$)/g;
var s = "First: foo Last: bar";
var m, res=[];
while (m=rx.exec(s)) {
  res.push([m[1].trim(),m[2].trim()].join(" "));
}
console.log(res);

See the regex demo at regex101.com. Details:

  • ([^:]+) - Group 1: one or more chars other than :
  • : - a :
  • \s* - 0+ whitespaces
  • (.*?) - Group 2: any 0+ chars other than line break chars, as few as possible
  • (?=\w+:|$) - followed with 1+ word chars and : or end of string.

Upvotes: 0

trincot
trincot

Reputation: 350272

As you want the colon removed, but still have the surrounding text in one group, you'll need to use some string manipulation after executing the regular expression:

var s = "First: foo Last: bar",
    re = /\s*([^:]*?)\s*:\s*([^:\s]*)/g,
    result = [];
while (match = re.exec(s)) {
    result.push(match[1] + ' ' + match[2]);
}

console.log(result);

Note that it can be ambiguous which word belongs where, when there are more spaces, for example in First: foo hello there: bar.

Upvotes: 2

Related Questions