gpt4 book ai didi

模式中的 Javascript 正则表达式多组匹配

转载 作者:搜寻专家 更新时间:2023-11-01 05:26:52 25 4
gpt4 key购买 nike

我有一个关于 Javascript 正则表达式忍者的问题:如何使用正则表达式分组来简化从字符串创建变量的过程?我目前可以在不使用任何分组的情况下使用它,但我希望看到更好的方法!

字符串是:

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

有人要吗?

最佳答案

当然..

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];

关于模式中的 Javascript 正则表达式多组匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2858832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com