2010-05-18 3 views
3

자바 정규식 닌자에 대한 질문이 있습니다. 어떻게 정규식 그룹화를 사용하여 문자열에서 변수 생성을 단순화 할 수 있습니까? 현재 그룹화를 사용하지 않고 작업하고 있지만 더 좋은 방법을보고 싶습니다!Javascript Regex 여러 그룹과 패턴이 일치합니다.

문자열은 다음과 같습니다 작동

var url = 'resources/css/main.css?detect=#information{width:300px;}'; 

코드는 다음과 같습니다

var styleStr = /[^=]+$/.exec(url).toString(); 
var id = /[^\#][^\{]+/.exec(styleStr).toString(); 
var property = /[^\{]+/.exec(/[^\#\w][^\:]+/.exec(styleStr)).toString(); 
var value = /[^\:]+/.exec(/[^\#\w\{][^\:]+[^\;\}]/.exec(styleStr)).toString(); 

이 제공 :

alert(id)  //information 
alert(property) //width 
alert(value) //300px 

모든 응시자?

+0

는 CSS 선택기 문법은 약간 더 복잡하다. (http://www.w3.org/TR/CSS2/grammar.html 참조) – Gumbo

답변

4

물론 ..

var url = 'resources/css/main.css?detect=#information{width:300px;}'; 
var matches = url.match(/#([^{]+){([^:]+):([^;]+)/); 
var id = matches[1]; 
var property = matches[2]; 
var value = matches[3]; 
+0

너희들은 빠르다. 그게 다예요, 고마워요! – mummybot

0
#(?<type>.+){(?<property>.*?):(?<value>.*?); 

Group "type": information  31  11 
Group "property": width  43  5 
Group "value": 300px 

JS [제이 regexbuddy 좋아] 사실

result = subject.match(/#([\s\S]+)\{([\s\S]*?):([\s\S]*?);/ig); 
관련 문제