2016-12-04 98 views
0

我試圖解析JavaScript中的文本輸入文件。
我想先將文件分成幾個部分,然後通過添加下面的代碼片段來填充表單。
我試圖找到一種方法來將輸入分成5個部分;聯繫信息(姓名,電話,電子郵件),目標,關鍵技能,就業歷史和教育。
而這裏存在的問題。我不是正則表達式專家。環顧網絡,我無法找到任何輕量級的javaScript庫來幫助解決這個問題。這是有意義的尋找關鍵字,如名稱:,然後匹配所有字符,直到遇到另一個關鍵字,如電話:但我不知道如何處理這個問題。解析從文本文件輸入到JSON格式的信息

function controller() { 

function loadFromFile(event) { 
    var fileInput = event.target.files[0]; 
    var textType = /txt.*/; 

    if (fileInput.type.match(textType)) { 
     var reader = new FileReader(); 
     reader.onload = function(evt) { 
      console.log(evt.target.result); 
     }; 
     reader.onerror = function(evt) { 
      errorLogger('cannot_read_file', 'The file specified cannot be read '); 
     }; 
     reader.readAsText(fileInput); 
    } else {} 
} 
$(':input[type="file"]').change(loadFromFile); 
}; 

Name: John Doe
Phone: (555) 555-5555
Email: [email protected]

OBJECTIVE Excel in a web developer career. 

KEY SKILLS Development: HTML5, JavaScript, Bootstrap, AngularJS, ReactJS, CSS3, Media Queries, 
Development Project Management: JIRA, Bitbucket, Confluence, Git, GitHub 

EMPLOYMENT HISTORY 
Title: Junior Web Developer 
Company: Apple Inc. 
Dates: June 2015 to September 2016 
* Developed responsive corporate websites 
* Did some cool stuff 
* Led team in closing out JIRA bugs 

Title: Web Development Intern 
Company: Google Inc. 
Dates: January 2015 to May 2015 
* Went on coffee runs for the team 
* Team record for longest keg stand 
* Once ate 82 cupcakes during a team building event 

EDUCATION Degree: BBA 
School: Michigan State University 
GPA: 2.2 Major: 
Computer Science Minor: Drinking 

回答

0

此正則表達式的作品,所提供的輸入始終是完全相同的格式。

/Name: ([a-zA-Z ]+)\nPhone: (\(\d{3}\) \d{3}-\d{4})\nEmail: ([email protected]+)\n{2}OBJECTIVE (.*)\n{2}KEY SKILLS (.*)\n{2}EMPLOYMENT HISTORY ((?:(?:(?:\W+|\s+|.*))*))/g;

https://regex101.com/r/Q5OUFw/2

我不是最好的使用JavaScript,但這似乎返回數組充分匹配。

let m; 
let matches =[]; 

while ((m = regex.exec(str)) !== null) 
{ 
    // This is necessary to avoid infinite loops with zero-width matches 
    if (m.index === regex.lastIndex) 
    { 
     regex.lastIndex++; 
    } 
    m.forEach((match, groupIndex) => { 
    matches.push(match); 
    }); 
} 

提供7組小組賽。

matches[0] =全場比賽

matches[1] =名稱

matches[2] =電話號碼

matches[3] =電子郵件

matches[4] =目標

matches[5] =技能

matches[6] =工作經歷