我有一个Javascript字符串:
let entries = `23-05-1990 Some heading
27-05-1990 Liar Liar
29-05-1990 Another Heading
30-05-1990 50/50
31-05-1990 My day`
使用正则表达式,我需要处理此字符串并生成两个数组:
// 1) date array:
date = ["23-05-1990","27-05-1990", "29-05-1990", "30-05-1990", "31-05-1990"]
// 2) headings array
headings = ["Some heading", "Liar Liar" ,"Another Heading", "50/50", "My day"]
到目前为止,这很简单:按换行符分隔,然后将每个单独的日期标题传递给正则表达式。获取日期和标题,并将它们附加到各自的数组中。
但是问题是我没有一致的数据格式。
一些数据采用这种格式。即标题早于日期
`Liar Liar 27-05-1990
Another Heading 29-05-1990
50/50 30-05-1990
My day 31-05-1990 `
标题和日期之间可能会有分隔符。
`23-05-1990 : Some heading
27-05-1990 : Yes Man`
`29-05-1990: Another Heading`
`30-05-1990 - 50/50
31-05-1990 - My day`
因此,日期和标题就在那里(我们不知道哪个先出现),但是分隔符可能存在也可能不存在。
也,
分隔符是下面列出的三个之一:
“ “ (空间), ”-” , ”:”
标题不能以字母或整数以外的任何字符开头或结束。
您可以匹配以下正则表达式。日期字符串将位于捕获组1或4中,另一个则为空。标题将位于捕获组2或3中,另一个将为空。
^(?:(\d{2}-\d{2}-\d{4}) *[-:]? *([A-Z\d].*)|([A-Z\d].*)(?<![ :-]) *[-:]? *(\d{2}-\d{2}-\d{4}))$
如链接所示,"$1$4"
返回日期字符串并"$2$3"
返回标题。
Javascript的regex引擎执行以下操作。
^ : assert beginning of string
(?: : begin non-capture group
(\d{2}-\d{2}-\d{4}) : match date and save to capture group 1
[ ]*[-:]?[ ]* : match 0+ spaces, optional '-' or ':',
0+ spaces
([A-Z\d].*) : match heading and save to capture group 2
| : or
([A-Z\d].*) : match heading and save to capture group 3
(?<![ :-]) : negative lookbehind asserts previous
character is neither ' ', ':' nor '-'
[ ]*[-:]?[ ]* : match 0+ spaces, optional '-' or ':',
0+ spaces
(\d{2}-\d{2}-\d{4}) : match date and save to capture group 4
) : end non-capture group
$ : assert end of string
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句