简体   繁体   English

在JavaScript中使用RegEx解析CSS字符串

[英]Parsing CSS string with RegEx in JavaScript

I have been trying to put together a simple RegEx and Googling for the last hour but I can't seem to find something that will work for me. 在过去的一个小时里,我一直在尝试将一个简单的RegEx和Googling放在一起,但似乎找不到适合我的东西。 I am looking to take a simple input string, say ".cSSRule { value: 'foo'; }" and split it into an array that looks like this: "[cssRule:value]" where the name of the rule is the key and the actual rule is value. 我正在寻找一个简单的输入字符串,说“ .cSSRule {value:'foo';}”,并将其拆分成一个看起来像这样的数组:“ [cssRule:value]”,其中规则的名称是关键而实际规则就是价值。 I'm not looking for a full-on parser (even though I know they exist) because that would be overkill for the simple strings that I am working with. 我并不是在寻找完整的解析器(即使我知道它们存在),因为这对于我正在使用的简单字符串来说可能会显得过大。 Would anyone kindly point me in the right direction? 有人能指出我正确的方向吗?

Thanks, 谢谢,

Blu 蓝光

In this case something like 在这种情况下,

var str = ".cssRule { value: 'foo'; }";
someArray.push( 
     ( (str.replace(/\.|}|;/g,''))
         .split(/{/)
         .join(':"')
         .replace(/\s/g,'')
         .replace(/.$/,'"')
     ); 
     /* =>"[cssRule:"value:'foo'"] */

would work. 会工作。 I don't think it's very generic though. 我认为这不是很通用。

This should do it: 应该这样做:

var str = ".cssRule { value: 'foo'; }";
var someObject = new Object;
var matches = str.match( /^\.(.*?){(.*?)}/ );
someObject[matches[1].replace(/ /g,'')] = matches[2].replace(/ /g,'');

'matches' becomes an array containing three elements: the first (index 0) is the full string of what it was matching against; “ matches”变成一个包含三个元素的数组:第一个(索引为0)是它所匹配的完整字符串; the second (index 1) matches everything between a period and the open brace, and the third (index 2) matches everything between the braces. 第二个(索引1)匹配句号和大括号之间的所有内容,第三个(索引2)匹配花括号之间的所有内容。

Where is the input string coming from? 输入字符串从哪里来? If it's a safe source (ie not coming from the user) just use a regex to strip the .cSSrule part and eval() the rest -- you have your complete associative array parsed and created for you. 如果是安全来源(即不是来自用户),则只需使用正则表达式剥离.cSSrule部分,然后剥离eval()其余部分,即可为您解析和创建完整的关联数组。

Edit: you'll need to replace ; 编辑:您需要替换; with , as well, except for the last occurence: ,还有,除了最后一个实例:

input
   .replace(/^(.*)(?={)/, '')
   .replace(/;(?!(\s)*?})/g, ',')
   .replace(';', '');
myCss = eval(input);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM