-3

I am trying to parse time bookings looking like this:

14687 - Project foobar, homeOffice 7:40 - 13:59
436 - Project barfoo, office 12:49 - 22:00

I want to grab all the text before the first occurrence of a time. The time has the 24 hour format HH:MM without leading zero. There can be one or two occurrences of such a timestamp. I figured this is the RegEx to match the time in this format:

(\d?\d:\d\d)

But how would I get the text before it? I am using javascript.

tzippy
  • 6,458
  • 30
  • 82
  • 151
  • 3
    You can use an anchor `^.*?(?=\s*\d?\d:\d\d)` – The fourth bird Sep 17 '22 at 11:32
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) -> https://www.regular-expressions.info/tutorial.html – Andreas Sep 17 '22 at 11:34

1 Answers1

1

I actually prefer a regex replacement approach here:

var input = "14687 - Project foobar, homeOffice 7:40 - 13:59";
var text = input.replace(/\s*\d{1,2}:\d{2} - \d{1,2}:\d{2}$/, "");
console.log(text);

This approach has an advantage over using match() with a capture group. With the above approach, we just return the entire input if it does not end in an hour range.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360