james
james

Reputation: 491

REGEX Ruby Rails

I have:

string = "4/28 - Declined 4/19 - Call with Bob, Joe and Steve 4/10 - Call scheduled for 10a on 4/18 4/9 - Wants to meet with Jay on 4/28 at 10:30a"

I am trying to produce an array that gives an array of four elements:

4/28 - Declined
4/19 - Call with Bob, Joe and Steve
4/10 - Call scheduled for 10a on 4/18
4/9 - Wants to meet with Jay on 4/28 at 10:30a

I'm having trouble with the following:

string.scan(/\d{1,2}+\/\d{1,2}[\s]?[-|:]+\s[A-Za-z\s\d]+ (?![\d{1,2}\/\d{1,2}]* -)/)

I get:

["4/19 - Call with ", "4/10 - Call scheduled for 10a on ", "4/9 - Wants to meet with Jay on "]

Upvotes: 0

Views: 49

Answers (3)

sawa
sawa

Reputation: 168081

string.split(%r{(\d+/\d+ - )}).drop(1).each_slice(2).map(&:join)

Output:

[
  "4/28 - Declined ",
  "4/19 - Call with Bob, Joe and Steve ",
  "4/10 - Call scheduled for 10a on 4/18 ",
  "4/9 - Wants to meet with Jay on 4/28 at 10:30a"
]

Upvotes: 1

user557597
user557597

Reputation:

It looks like the natural separator is this \d{1,2}+ / \d{1,2} \s? [-:]+

So you can use that in a negative assertion to get the body of the message.

\d{1,2}+/\d{1,2}\s?[-:]+(?:(?!\d{1,2}+/\d{1,2}\s?[-:]+)[\S\s])*

https://regex101.com/r/o8Grdx/1

Formatted

 \d{1,2}+ / \d{1,2} \s? [-:]+ 
 (?:
      (?! \d{1,2}+ / \d{1,2} \s? [-:]+ )
      [\S\s] 
 )*

Upvotes: 0

arieljuod
arieljuod

Reputation: 15838

Try this regexp:

(\d{1,2}\/\d{1,2}.+?(?:(?=\d{1,2}\/\d{1,2} - )|\z))

Check the result here http://rubular.com/r/04VL4Qs7Kb

It returns this matches:

Match 1
1.  4/28 - Declined
Match 2
1.  4/19 - Call with Bob, Joe and Steve
Match 3
1.  4/10 - Call scheduled for 10a on 4/18
Match 4
1.  4/9 - Wants to meet with Jay on 4/28 at 10:30a

The important parts:

it starts with a "date" and then anything else (note the last ?, it makes the .+ or .* be "non-greedy")

\d{1,2}\/\d{1,2}.+?

up until the next "date followed by a dash" OR the end of the line (this OR is important, or you won't get the last match)

(?=\d{1,2}\/\d{1,2} - )|\z)

that ?: is there to ignore the group on the result

(?:(...))

otherwise you get a blank second group on each match

Match 1
1.  4/28 - Declined
2.   
Match 2
1.  4/19 - Call with Bob, Joe and Steve
2.   
Match 3
1.  4/10 - Call scheduled for 10a on 4/18
2.   
Match 4
1.  4/9 - Wants to meet with Jay on 4/28 at 10:30a
2.   

Upvotes: 2

Related Questions