Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split on newlines AND commas AND semi-colons

I'd like to take a textarea's worth of people's names, entered by a user, and separate them into items in an array.

Take a theoretically possible input:

people = "Abby Andrews, Ben \r\nCharlie Connors    Daphne D., Ernie E. Engels; Faye\r\n\r\nGary Gomez"

array = people.split('??')

How can the regex be constructed to successfully split a crazy chain like the above?

Should be split:

  • \r, \n, \r\n
  • comma (,) or semi-colon (;)
  • multiple spaces

Should not be split:

  • period (this could be someone's initial)
  • single space (could be separating first and last names)

I tried people.split(/\r\n,;/), people.split(/,;\r\n/), and combinations thereof but none produced the result.

like image 886
sscirrus Avatar asked Jan 22 '12 14:01

sscirrus


People also ask

How do you match a semicolon in RegEx?

Thus, if you use a semicolon (;) in a keyword expression, it will split the keywords into multiple parts. Semicolon is not in RegEx standard escape characters. It can be used normally in regular expressions, but it has a different function in HES so it cannot be used in expressions.

How do you split a string into a new line in HTML?

To split a string by newline, call the split() method passing it the following regular expression as parameter - /\r?\ n/ . The split method will split the string on each occurrence of a newline character and return an array containing the substrings.

How do you use commas in RegEx?

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ; . The closing ] indicates the end of the character set. The plus + indicates that one or more of the "previous item" must be present.


1 Answers

Try

array = people.split(
    /\s*[,;]\s* # comma or semicolon, optionally surrounded by whitespace
    |           # or
    \s{2,}      # two or more whitespace characters
    |           # or
    [\r\n]+     # any number of newline characters
    /x)
like image 55
Tim Pietzcker Avatar answered Oct 15 '22 10:10

Tim Pietzcker