我有这个字符串:
" Lorem ipsum dolor sit amet,{{foo.name}} consectetuer adipiscing elit。 Aenean commodo ligula eget dolor。 {{bar.address}} Aenean massa。 Cum sociis natoque penatibus et magnis dis parturient montes,nascetur ridiculus mus。 Donec quam felis,ultricies nec,{{dummy.company}} pellentesque eu,pretium quis,sem。 "
我需要提取用双花括号括起来的字符串(foo.name,bar.address,dummy.company),它由2个由句点分隔的子字符串组成。我怎么能用正则表达式做到这一点?
仍然是正则表达式的初学者,并尝试了/ [az]。[ - z],但没有得到正确的匹配。
答案 0 :(得分:1)
使用regexp101.com:
$re = '/({{.*?}})/';
$str = 'Lorem ipsum dolor sit amet, {{foo.name}} consectetuer adipiscing elit.
Aenean commodo ligula eget dolor. {{bar.address}} Aenean massa. Cum sociis
natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Donec quam felis, ultricies nec, {{dummy.company}} pellentesque eu, pretium
quis, sem.';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
oops是php - JavaScript是:
const regex = /({{.*?}})/g;
const str = `Lorem ipsum dolor sit amet, {{foo.name}} consectetuer adipiscing elit.
Aenean commodo ligula eget dolor. {{bar.address}} Aenean massa. Cum sociis
natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Donec quam felis, ultricies nec, {{dummy.company}} pellentesque eu, pretium
quis, sem. `;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}