使用Javascript正则表达式解析css渐变规则

fol*_*bis 4 javascript css regex gradient

在我的css文件中我有渐变规则,像这样:

background-image:linear-gradient(to right, #FF0000 0%, #00FF00 20px, rgb(0, 0, 255) 100%);
Run Code Online (Sandbox Code Playgroud)

我想得到这个字符串的所有部分.预期产出是:

linear-gradient
to right
#FF0000 
0%, 
#00FF00 
20px, 
rgb(0, 0, 255) 
100%
Run Code Online (Sandbox Code Playgroud)

对我来说,整个字符串的工作太难了所以我决定把它分成几部分.

线性梯度

.*gradient[^\(]?
Run Code Online (Sandbox Code Playgroud)

颜色

rgb ?\([ 0-9.%,]+?\)|#[0-9a-fA-F]{3,6}\s[0-9]{1,3}[%|px]|#[0-9a-fA-F]{3,6}|(aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow){1}(\s[0-9]{1,3}\s*[%|px]?)?
Run Code Online (Sandbox Code Playgroud)

(?<=\()(.*(top|left|right|bottom|center).*?)(?=,)
Run Code Online (Sandbox Code Playgroud)

但最后的正则表达式在JS中不起作用,因为它没有正则表达式.不久,我需要在这里得到"("和","

Dea*_*lor 11

解析CSS可能要复杂得多,几乎没有什么可记住的:

  • 避免编写解析器 - 其他人可能已经编写了一个解析器(搜索).
  • 如果您不控制输入源或使用输入样本彻底测试输入源,则解析器可能会失败.
  • 在渐变的情况下,您可以具有"角度"以及"右侧"的"角侧".
  • 有一个未知数量的色标(最小1).
  • 你永远不会可能要包括的CSS颜色正则表达式的完整列表(例如red,blue等).
  • 您应该查看MDN以获取语法变体的详细信息,下面的示例代码仅支持标准语法.
  • 正则表达式支持和错误因浏览器和版本而异 - 使用所有样本测试目标浏览器.

好的,所以这是一个疯狂的例子,说明你如何"使用正则表达式"解析渐变 - 我不是说你应该这样做.

在这里,我在代码中构建我的正则表达式,以保持代码的某种程度的可读性和可维护性.

test_this_thing函数的最终输出console.log(result);如下:

输入:

background-image:linear-gradient(to right bottom, #FF0000 0%, #00FF00 20px, rgb(0, 0, 255) 100%);

输出:

{
   original:"to right bottom, #FF0000 0%, #00FF00 20px, rgb(0, 0, 255) 100%",
   line:"to right bottom",
   sideCorner:"right bottom",
   colorStopList:[
      {
         color:"#FF0000",
         position:"0%"
      },
      {
         color:"#00FF00",
         position:"20px"
      },
      {
         color:"rgb(0, 0, 255)",
         position:"100%"
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

注意输出包括original属性 - 这看起来像输入 - 但如果输入的一部分不匹配input,则original值和值将不同; 注意解析器中可能存在的错误.

这是一个来源:

/**
 * Utility combine multiple regular expressions.
 *
 * @param {RegExp[]|string[]} regexpList List of regular expressions or strings.
 * @param {string} flags Normal RegExp flags.
 */
var combineRegExp = function (regexpList, flags) {
    var i,
        source = '';
    for (i = 0; i < regexpList.length; i++) {
        if (typeof regexpList[i] === 'string') {
            source += regexpList[i];
        } else {
            source += regexpList[i].source;
        }
    }
    return new RegExp(source, flags);
};

/**
 * Generate the required regular expressions once.
 *
 * Regular Expressions are easier to manage this way and can be well described.
 *
 * @result {object} Object containing regular expressions.
 */
var generateRegExp = function () {
    // Note any variables with "Capture" in name include capturing bracket set(s).
    var searchFlags = 'gi', // ignore case for angles, "rgb" etc
        rAngle = /(?:[+-]?\d*\.?\d+)(?:deg|grad|rad|turn)/, // Angle +ive, -ive and angle types
        rSideCornerCapture = /to\s+((?:(?:left|right)(?:\s+(?:top|bottom))?))/, // optional 2nd part
        rComma = /\s*,\s*/, // Allow space around comma.
        rColorHex = /\#(?:[a-f0-9]{6}|[a-f0-9]{3})/, // 3 or 6 character form
        rDigits3 = /\(\s*(?:\d{1,3}\s*,\s*){2}\d{1,3}\s*\)/,// "(1, 2, 3)"
        rDigits4 = /\(\s*(?:\d{1,3}\s*,\s*){2}\d{1,3}\s*,\s*\d*\.?\d+\)/,// "(1, 2, 3, 4)"
        rValue = /(?:[+-]?\d*\.?\d+)(?:%|[a-z]+)?/,// ".9", "-5px", "100%".
        rKeyword = /[_a-z-][_a-z0-9-]*/,// "red", "transparent", "border-collapse".
        rColor = combineRegExp([
            '(?:', rColorHex, '|', '(?:rgb|hsl)', rDigits3, '|', '(?:rgba|hsla)', rDigits4, '|', rKeyword, ')'
        ], ''),
        rColorStop = combineRegExp([rColor, '(?:\\s+', rValue, '(?:\\s+', rValue, ')?)?'], ''),// Single Color Stop, optional %, optional length.
        rColorStopList = combineRegExp(['(?:', rColorStop, rComma, ')*', rColorStop], ''),// List of color stops min 1.
        rLineCapture = combineRegExp(['(?:(', rAngle, ')|', rSideCornerCapture, ')'], ''),// Angle or SideCorner
        rGradientSearch = combineRegExp([
            '(?:(', rLineCapture, ')', rComma, ')?(', rColorStopList, ')'
        ], searchFlags),// Capture 1:"line", 2:"angle" (optional), 3:"side corner" (optional) and 4:"stop list".
        rColorStopSearch = combineRegExp([
            '\\s*(', rColor, ')', '(?:\\s+', '(', rValue, '))?', '(?:', rComma, '\\s*)?'
        ], searchFlags);// Capture 1:"color" and 2:"position" (optional).

    return {
        gradientSearch: rGradientSearch,
        colorStopSearch: rColorStopSearch
    };
};

/**
 * Actually parse the input gradient parameters string into an object for reusability.
 *
 *
 * @note Really this only supports the standard syntax not historical versions, see MDN for details
 *       https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
 *
 * @param regExpLib
 * @param {string} input Input string in the form "to right bottom, #FF0 0%, red 20px, rgb(0, 0, 255) 100%"
 * @returns {object|undefined} Object containing break down of input string including array of stop points.
 */
var parseGradient = function (regExpLib, input) {
    var result,
        matchGradient,
        matchColorStop,
        stopResult;

    // reset search position, because we reuse regex.
    regExpLib.gradientSearch.lastIndex = 0;

    matchGradient = regExpLib.gradientSearch.exec(input);
    if (matchGradient !== null) {
        result = {
            original: matchGradient[0],
            colorStopList: []
        };

        // Line (Angle or Side-Corner).
        if (!!matchGradient[1]) {
            result.line = matchGradient[1];
        }
        // Angle or undefined if side-corner.
        if (!!matchGradient[2]) {
            result.angle = matchGradient[2];
        }
        // Side-corner or undefined if angle.
        if (!!matchGradient[3]) {
            result.sideCorner = matchGradient[3];
        }


        // reset search position, because we reuse regex.
        regExpLib.colorStopSearch.lastIndex = 0;

        // Loop though all the color-stops.
        matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]);
        while (matchColorStop !== null) {

            stopResult = {
                color: matchColorStop[1]
            };

            // Position (optional).
            if (!!matchColorStop[2]) {
                stopResult.position = matchColorStop[2];
            }
            result.colorStopList.push(stopResult);

            // Continue searching from previous position.
            matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]);
        }
    }

    // Can be undefined if match not found.
    return result;
};

var test_this_one = function (regExpLib, input) {
    var result,
        rGradientEnclosedInBrackets = /.*gradient\s*\(((?:\([^\)]*\)|[^\)\(]*)*)\)/,// Captures inside brackets - max one additional inner set.
        match = rGradientEnclosedInBrackets.exec(input);

    if (match !== null) {
        // Get the parameters for the gradient
        result = parseGradient(regExpLib, match[1]);
        if (result.original.trim() !== match[1].trim()) {
            // Did not match the input exactly - possible parsing error.
            result.parseWarning = true;
        }
    } else {
        result = "Failed to find gradient";
    }

    return result;
};

var test_this_thing = function () {

    var result = [],
        regExpLib = generateRegExp(),
        testSubjects = [
            // Original question sample
            'background-image:linear-gradient(to right bottom, #FF0000 0%, #00FF00 20px, rgb(0, 0, 255) 100%);',
            // Sample to test RGBA values (1)
            'background-image:linear-gradient(to right bottom, rgba(255, 0, 0, .1) 0%, rgba(0, 255, 0, 0.9) 20px);',
            // Sample to test optional gradient line
            'background-image:linear-gradient(#FF0000 0%, #00FF00 20px, rgb(0, 0, 255) 100%);',
            // Angle, named colors
            'background: linear-gradient(45deg, red, blue);',
            // Gradient that starts at 60% of the gradient line
            'background: linear-gradient(135deg, orange, orange 60%, cyan);',
            // Gradient with multi-position color stops
            'background: linear-gradient(to right, red 20%, orange 20% 40%, yellow 40% 60%, green 60% 80%, blue 80%);'
        ];
    for (var i = 0; i < testSubjects.length; i++) {
        result.push(test_this_one(regExpLib, testSubjects[i]));
    }

    console.log(result);
};
test_this_thing();
Run Code Online (Sandbox Code Playgroud)