Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting string from the first occurrence of a character

I have multiple lines of text in log files in this kind of format:

topic, this is the message part, with, occasional commas.

How can I split the string from the first comma so I would have the topic and the rest of the message in two different variables?

I've tried using this kind of split, but it doesn't work when there's more commas in the message part.

[topic, message] = whole_message.split(",", 2);
like image 443
Seerumi Avatar asked May 25 '11 21:05

Seerumi


People also ask

How do you split a string on the first occurrence of certain characters?

Using the split() Method For example, if we put the limit as n (n >0), it means that the pattern will be applied at most n-1 times. Here, we'll be using space (” “) as a regular expression to split the String on the first occurrence of space.

How do you split based on first occurrence?

Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .

How do you split a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do you extract the first letter of a string?

Get the First Letter of the String You should use the charAt() method, at index 0, to select the first character of the string. NOTE: charAt is preferable than using [ ] (bracket notation) as str.


3 Answers

Use a regex that gets "everything but the first comma". So:

whole_message.match(/([^,]*),(.*)/)

[1] will be the topic, [2] will be the message.

like image 77
Ian Avatar answered Oct 18 '22 22:10

Ian


That sort of decomposing assignment doesn't work in Javascript (at the present time). Try this:

var split = whole_message.split(',', 2);
var topic = split[0], message = split[1];

edit — ok so "split()" is kind-of broken; try this:

var topic, message;
whole_message.replace(/^([^,]*)(?:,(.*))?$/, function(_, t, m) {
  topic = t; message = m;
});
like image 23
Pointy Avatar answered Oct 18 '22 20:10

Pointy


Here!

String.prototype.mySplit = function(char) { 
  var arr = new Array(); 
  arr[0] = this.substring(0, this.indexOf(char)); 
  arr[1] = this.substring(this.indexOf(char) + 1); 
  return arr; 
}

str = 'topic, this is the message part, with, occasional commas.'
str.mySplit(',');
-> ["topic", " this is the message part, with, occasional commas."]
like image 3
josh.trow Avatar answered Oct 18 '22 20:10

josh.trow