简体   繁体   English

JS RegEx 返回一个带连字符的单词,然后是另一个单词/值

[英]JS RegEx to return a hyphenated word and then another word/value

I'm having some RegEx trouble, but I am aiming for this snippet of code to read an input such as "background-colour:red;"我遇到了一些正则表达式问题,但我的目标是让这段代码读取诸如"background-colour:red;"类的输入。 , validate the syntax, then take "background-colour" and "red" into an array. ,验证语法,然后将“背景颜色”和“红色”放入数组中。 It currently returns ["background-colour"] , but not red, and I've spent around an hour to try and figure it out.它目前返回["background-colour"] ,但不是红色,我花了大约一个小时试图弄清楚。 Could anyone help or point me in the right direction?任何人都可以帮助或指出我正确的方向吗? I've managed to get simple ones like "opacity:1;"我设法得到了像"opacity:1;"这样简单的东西。 and "colour:red;""colour:red;" to work but the hyphen has thrown a wrench in it.工作,但连字符在其中扔了一个扳手。

 let ed = document.getElementById("editor").innerText; 
 let dest = document.getElementById("destination");

//irrelevent code stripped here 

    regex3 = new RegExp(/^[a-zA-Z]+-[a-zA-Z]+:[a-zA-Z]+;$/i);
        
        //irrelevent code stripped here 

        else if (regex3.test(ed)) {
                    console.log("valid input");
                    let pattern = /\w+\-\w+/g;
        
                    let temp = ed.match(pattern);
                    console.log(temp);
        
                    let att = temp[0];
        
                    let quant = String(temp[1]);
        
                    console.log(att);
                    console.log(temp);
                    dest.style.setProperty(att, quant);
                    

Test with regex for validity and the use split() for getting property key and value in an array.使用正则表达式测试有效性并使用 split() 获取数组中的属性键和值。

const regex = /^\w+(-\w+:\w+)?/

const input = 'background-colour:red'

const valid = regex.test(input)
let ouput = []
if(valid){
    ouput = input.split(":")
}
console.log(ouput)

You're using dest.style.setProperty in your example, so I'm assuming you're working with CSS properties.您在示例中使用dest.style.setProperty ,所​​以我假设您正在使用 CSS 属性。 This method will get you the property and the value you need and works with any CSS value.此方法将为您提供所需的属性和值,并适用于任何 CSS 值。

// test strings
const singleHyphenTest= 'background-color:red;';
const multipleHyphenTest = 'grid-template-columns:60px 60px;';
const noHyphenTest = 'color: red;';
const functionTest = 'width: calc(1rem + 20px);';
const customPropertyTest = 'background-color: var(--main-bg-color);';
const ANY_SYNTAX_WORKS = 'blablabla:stackoverflow;'

// either split the strings on : or ;
const pattern = /[:;]+/;
const singleGroup = singleHyphenTest.split(pattern);
const multipleGroup = multipleHyphenTest.split(pattern);
const noneGroup = noHyphenTest.split(pattern);
const functionGroup = functionTest.split(pattern);
const customGroup = customPropertyTest.split(pattern);
const anyGroup = ANY_SYNTAX_WORKS.split(pattern);

console.log(singleGroup);   // ['background-color', 'red', '']
console.log(multipleGroup); // ['grid-template-columns', '60px 60px', '']
console.log(noneGroup);     // ['color', ' red', '']
console.log(functionGroup); // ['width', ' calc(1rem + 20px)', '']
console.log(customGroup);   // ['background-color', ' var(--main-bg-color)', '']
console.log(anyGroup);      // ['blablabla', 'stackoverflow', '']

You can check if the CSS is 'valid' by checking if the array length is equal to 3:您可以通过检查数组长度是否等于 3 来检查 CSS 是否“有效”:

const ed = 'background-color:red;'; 
const pattern = /[:;]+/; 
const groups = ed.split(pattern); 
if (3 === groups.length) {     
    const [cssProperty, cssValue] = groups;     
    console.log(cssProperty); // background-color  
    console.log(cssValue); // red

    // do your stuff here
    // dest.style.setProperty(cssProperty, cssValue);  
}

Again: this solution (and the regex in your example) does not validate the syntax!同样:此解决方案(以及您示例中的正则表达式)不验证语法! It only does some basic pattern matching.它只做一些基本的模式匹配。 In order to validate the CSS syntax, you would have to do a lot more to catch all edge cases..为了验证 CSS 语法,你必须做更多的事情来捕捉所有边缘情况。

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

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