获取两个字符之间的内容
Getting the content between two characters
所以我有这个(示例)字符串:1234VAR239582358X
我想获取 VAR 和 X 之间的内容。我可以使用 .replace(/VAR.*X/, "replacement");
轻松替换它
但是,我如何将 /VAR.*X/
作为变量?
我想你要找的可能是
string.match(/VAR(.*)X/)[1]
.* 两边的括号标记了一个组。这些组在 match
创建的数组中返回:)
如果您只想替换“VAR”和“X”之间的内容,可以是
string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");
或更通用:
string.replace(/(VAR).*(X)/, "replacement");
您可以尝试使用 RegExp class、new RegExp(`${VAR}.*X`)
您可以像这样将其存储为变量,
const pattern = "VAR.*X";
const reg = new RegExp(pattern);
然后使用,
.replace(reg, "replacement");
如果你
want to get what's in between VAR and X
然后使用 .*
将完成给定示例字符串的工作。
但注意是匹配到字符串末尾,然后回溯到第一次出现的X
它可以匹配,是字符串中X字符的最后一次出现,也可能匹配很多。
如果只想匹配数字,可以使用 VAR(\d+)X
匹配捕获组中的 1+ 个数字
const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
或者您可以使用取反字符 class VAR([^\r\nX]+)X
匹配直到第一次出现 X
字符
const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
所以我有这个(示例)字符串:1234VAR239582358X
我想获取 VAR 和 X 之间的内容。我可以使用 .replace(/VAR.*X/, "replacement");
轻松替换它
但是,我如何将 /VAR.*X/
作为变量?
我想你要找的可能是
string.match(/VAR(.*)X/)[1]
.* 两边的括号标记了一个组。这些组在 match
创建的数组中返回:)
如果您只想替换“VAR”和“X”之间的内容,可以是
string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");
或更通用:
string.replace(/(VAR).*(X)/, "replacement");
您可以尝试使用 RegExp class、new RegExp(`${VAR}.*X`)
您可以像这样将其存储为变量,
const pattern = "VAR.*X";
const reg = new RegExp(pattern);
然后使用,
.replace(reg, "replacement");
如果你
want to get what's in between VAR and X
然后使用 .*
将完成给定示例字符串的工作。
但注意是匹配到字符串末尾,然后回溯到第一次出现的X
它可以匹配,是字符串中X字符的最后一次出现,也可能匹配很多。
如果只想匹配数字,可以使用 VAR(\d+)X
const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
或者您可以使用取反字符 class VAR([^\r\nX]+)X
X
字符
const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}