我正在尝试寻找一种方法来从字符串输入中捕获数据,并使其易于使用容器。例如:
everything_avg = Article.objects.filter(removed_date__isnull=False)\
.aggregate(
avg_score=Avg(
F('removed_date') - F('created_on'),
output_field=models.DateTimeField()
)
)
return everything_avg
我知道如何根据正则表达式测试字符串并返回是否匹配:
var message = "Sarah has been promoted to Superintendent";
但是我为弄清楚如何找到正则表达式匹配的索引以将其放置在对象中而感到困惑:
message.test(\[a-zA-Z]+ has been promoted to [a-zA-Z]+\g);
我觉得答案就在我脑细胞的尖端,但是我很茫然。例如,要采取什么步骤来捕获字符串中第一个通配符的索引,将该单词分开,然后对下一个数据段进行处理(足够灵活以处理多达9个左右的“通配符”)? / p>
答案 0 :(得分:0)
var message = "Sarah has been promoted to Superintendent";
groups = /([a-zA-Z]+) has been promoted to ([a-zA-Z]+)/.exec(message)
会给你
["Sarah has been promoted to Superintendent", "Sarah", "Superintendent"]
通过删除g
标志,您可以让它仅匹配一次,从而将与括号内的子模式匹配的子字符串放入数组中,并使用exec
而不是test
来获得返回数组而不是布尔值。
如果match
不为null,则从左到右的第一个带括号的子模式将在match[1]
中,而第二个在match[2]
中。
答案 1 :(得分:0)
是的,您需要捕获组。
var message = "Sarah has been promoted to Superintendent";
var match = /([a-zA-Z]+) has been promoted to ([a-zA-Z]+)/g.exec(message);
console.log(match[1], match[2]);
输出
Sarah Superintendent
有关RegExp.exec()
的更详尽说明,请参见here。
答案 2 :(得分:0)
签出String.prototype.match
:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
let message = "Sarah has been promoted to Superintendent";
let [, name, position] = message.match(/([a-zA-Z]+) has been promoted to ([a-zA-Z]+)/);
let promotion = {name, position};
console.log(promotion);