![](/img/trans.png)
[英]JS regex to replace empty lines within SCSS between closing curly brace and opening class/id
[英]Regex to Match lines with a Curly Brace
我正在嘗試編寫一個正則表達式,該正則表達式將基本上通過一個字符串並提取某些組,以供以后使用。
我有一個示例字符串正在使用:
foo bar baz
foo {
bar
baz
} asdf
a {
b
c
} d
我希望輸出匹配為:
foo bar baz
下一個:
foo { bar baz } asdf
最后:
a { b c } d
所以我一直在處理的正則表達式是:/( /(^[\\s\\S]+?\\}|\\S.+)\\n?/g
但這仍然行不通。 可以提供正則表達式幫助,或建議使用JavaScript更好的方法嗎?
我覺得最適合此任務的正則表達式是.*
(在javascript中, .
不匹配換行符,因此.*
基本上表示整行。),然后逐行評估內容。 正則表達式在嵌套匹配和解析出來時可能會遇到很多麻煩。
這樣的事情可能對您有用 : http : //jsfiddle.net/qfLs7s01/3/ 。 它是逐行的非常基本的解析器。
var funks = {} // this is an object to hold all the parsed out data
var funkname;
var nest = [];
var content = document.getElementById('container').value;
var cgather = content.replace(/(.*)/igm,function(match, p1) {
p1 = p1.trim();
if (p1.substr(p1.length-1,1) == "{") {
funks[p1] = [];
funkname = p1;
nest.push(p1);
} else if (p1.substr(0,1) == "}") {
if (nest.length > 0) {
funkname = nest[nest.length-2];
nest.splice(-1,1);
} else {
nest = [];
}
} else {
if (p1.length) funks[funkname].push(p1)
}
return p1;
})
console.log(funks);
唯一的麻煩是它如何處理重復的函數名稱。
foo {
foo content
} foo
bar {
bar content
} bar
foo {
more foo content
}
會產生類似{foo: ["foo content","more foo content"], bar: ["bar content"]}
的數組結構
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.