正则表达式在特定字符处停止,return 如果不匹配则为 null
Regular expression to stop at specific character, return null if doesn't match
我有这个字符串:
|AL;GF=0;ID=17;AF=122|CT;GF=0;ID=15;AF=123|BD;GF=0;ID=1;AF=124|
如果 CT 块(在 | 之间有 CT;)ID=1,我想匹配,我试过:
/\|CT;.*?ID=1;(?=.*\|)/
但不起作用。
代码:
let string = '|AL;GF=0;ID=17;AF=122|CT;GF=0;ID=15;AF=123|BD;GF=0;ID=1;AF=124|'
console.log(string.match(/\|CT;.*?ID=1;(?=.*\|)/g))
// return ['|CT;GF=0;ID=15;AF=123|BD;GF=0;ID=1;']
// expected null
有人可以帮助我吗?
您可以使用
/\|CT;[^|]*ID=1;/
参见regex demo。
详情:
\|CT;
- |CT;
字符串
[^|]*
- 除了 |
字符 之外的零个或多个字符
ID=1;
- 固定字符串。
查看 JavaScript 演示:
const strings = [
'|AL;GF=0;ID=17;AF=122|CT;GF=0;ID=15;AF=123|BD;GF=0;ID=1;AF=124|',
'|AL;GF=0;ID=17;AF=122|CT;GF=0;ID=1;AF=123|BD;GF=0;ID=1;AF=124|'
]
for (const string of strings) {
console.log(string.match(/\|CT;[^|]*ID=1;/)?.[0]);
}
我有这个字符串:
|AL;GF=0;ID=17;AF=122|CT;GF=0;ID=15;AF=123|BD;GF=0;ID=1;AF=124|
如果 CT 块(在 | 之间有 CT;)ID=1,我想匹配,我试过:
/\|CT;.*?ID=1;(?=.*\|)/
但不起作用。
代码:
let string = '|AL;GF=0;ID=17;AF=122|CT;GF=0;ID=15;AF=123|BD;GF=0;ID=1;AF=124|'
console.log(string.match(/\|CT;.*?ID=1;(?=.*\|)/g))
// return ['|CT;GF=0;ID=15;AF=123|BD;GF=0;ID=1;']
// expected null
有人可以帮助我吗?
您可以使用
/\|CT;[^|]*ID=1;/
参见regex demo。
详情:
\|CT;
-|CT;
字符串[^|]*
- 除了|
字符 之外的零个或多个字符
ID=1;
- 固定字符串。
查看 JavaScript 演示:
const strings = [
'|AL;GF=0;ID=17;AF=122|CT;GF=0;ID=15;AF=123|BD;GF=0;ID=1;AF=124|',
'|AL;GF=0;ID=17;AF=122|CT;GF=0;ID=1;AF=123|BD;GF=0;ID=1;AF=124|'
]
for (const string of strings) {
console.log(string.match(/\|CT;[^|]*ID=1;/)?.[0]);
}