[英]Javascript: Read text file into array, split by regular expression
我需要解析一個看起來像日志的純文本文件:
11/04/2015 11:45:01: James: Cheers guys, enjoy the weekend!
11/04/2015 12:08:55: Sarah: Sounds good James
11/04/2015 12:09:24: Sarah: What are the details of the trip?
11/04/2015 12:19:06: Leah: Driving up on Friday.
Saturday we'll hit the beach.
Sunday paaaaarty!
11/04/2015 12:29:54: James: Nice.
我目前正在通過換行符進行解析:
var messages = data.split('\n');
但這在消息包含換行符的地方不起作用(請參見上面Leah的消息)。
解析每個新條目的正確方法是什么? 某種正則表達式日期/時間匹配? 還是如上所述解析日期的某些正則表達式?
感謝您的幫助。
我認為您可以在這里嘗試-
如果每個行的統計信息都具有日期格式,則將其后面的部分作為字符串使用,直到以另一種日期格式結束。
不要使用
\\n
分割,而是使用mm/dd/yyyy hh:mm:ss:
格式的日期。邏輯需要申請以下類型,因為您的文本屬於以下所述的這種類型-
日期格式開始>> 內容 <<日期格式結束
使用本指南制作自己的正則表達式。 http://www.w3schools.com/jsref/jsref_obj_regexp.asp
Try this Regular Expression to split /[0-9]+\/[0-9]+\/[0-9]* [0-9]*\:[0-9]*\:[0-9]*\:/g
var re = /[0-9]+\/[0-9]+\/[0-9]* [0-9]*\:[0-9]*\:[0-9]*\:/g;
var str = '11/04/2015 11:45:01: James: Cheers guys, enjoy the weekend!\n\n11/04/2015 12:08:55: Sarah: Sounds good James\n\n11/04/2015 12:09:24: Sarah: What are the details of the trip?\n\n11/04/2015 12:19:06: Leah: Driving up on Friday.\nSaturday we\'ll hit the beach.\nSunday paaaaarty!\n\n11/04/2015 12:29:54: James: Nice.';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.