Reputation: 336
I'm trying to split a string at every occurrence of a specific pattern. I have a string like this one:
91.240.109.42FrancePrestashop PI block
2021-06-02213.186.52.66FrancePrestaShop
2012-06-29
And I want to split the string at every occurrence of the date format yyyy-mm-dd
mantaining the date in the splitted array, so the result I want to obtain is this one:
[91.240.109.42FrancePrestashop PI block 2021-06-02,213.186.52.66FrancePrestaShop 2012-06-29]
I have tried to split based on the date format but it does not work:
var splitted_string= result.split(/^\d{4}-\d{2}-\d{2}$/)
Upvotes: 0
Views: 941
Reputation: 626845
You can use
const text = `91.240.109.42FrancePrestashop PI block
2021-06-02213.186.52.66FrancePrestaShop
2012-06-29`;
console.log( text.split(/(?<=\d{4}-\d{2}-\d{2})/).map(x=>x.replaceAll("\n"," ")) )
The (?<=\d{4}-\d{2}-\d{2})
pattern is a positive lookbehind that matches a location that is immediately preceded with four digits, -
, two digits, -
and two digits.
See this regex demo.
With .map(x=>x.replaceAll("\n"," ")
, you replace each LF Char with a space.
Upvotes: 1
Reputation: 521249
Use match
here, with the following regex pattern:
[\s\S]+?(?:\d{4}-\d{2}-\d{2}|$)
This will match all content up until the first date, repeteadly through the text.
var input = `91.240.109.42FrancePrestashop PI block
2021-06-02213.186.52.66FrancePrestaShop
2012-06-29`
var matches = input.match(/[\s\S]+?(?:\d{4}-\d{2}-\d{2}|$)/g);
console.log(matches);
Note that I use logic such that should the input not end in a date, the final split value would still be included.
Upvotes: 1