2013-10-08 71 views
0

我想根据标题按照特定格式(==HEADER==)将字符串分割为多个部分。这里的输入字符串会是什么样子:根据标题将字符串分割为多个部分

== Section header == 
Text inside section 
=== Maybe a nested section === 
With some more text 
And more text 
==Then the next section header, perhaps w/o spaces between text and equals signs== 
With text inside it 

这是我想要的输出:

[ 
    '== Section header == 
    Text inside section 
    === Maybe a nested section === 
    With some more text 
    And more text', 
    '==Then the next section header, without spaces between text and equals signs== 
    With text inside it' 
] 

我试图做

pagetext = "== Test header ==\n Some test text, with random equals signs==newlines\n or whatever\n ==Another header == \n more text,\nnewlines\nohmy" 
sections = []; 
section_re = /==\s*(\s*[^=]*)\s*==/g; 
var section_headers = pagetext.match(section_re); 
for (var i = 0; i < section_headers.length; i++) { 
    var section_start = pagetext.indexOf(section_headers[i]); 
    var section_text = pagetext.substring(section_start); 
    if (i < section_headers.length - 1) { 
     var section_end = section_text.substring(section_headers[i].length).indexOf(section_headers[i + 1]) + section_headers[i].length; 
     section_text = section_text.substring(0, section_end); 
    } 
    sections.push(section_text); 
} 

但它分割在“随机等号”迹象,给我:

["== Test header ==\n Some...ith random equals signs", "==newlines\n or whatever...ore text,\nnewlines\nohmy"] 

这不是 对。我有一种感觉,我的代码可能太复杂 - 有没有更好的方法来做到这一点?

回答

1

result = subject.match(/^==[^=]*?==$((\r?\n?)(?!==[^=]).*)*/img); 
+0

哇一展身手,看起来超赞!快速的问题:它会突破部分头像'==你好= Goodbye =='(它仍然是合法的头)? – tehsockz

+1

ok试试 'result = subject.match(/ \??\ n?)(?!== [^ =])。*)*/img);' – Brendan