匹配正则表达式,直到第一次出现特殊字符 '->'
Match regex until the first occurrence of special character '->'
我是正则表达式的新手,一直在尝试匹配表达式直到出现特殊的 character/s。如果在特殊字符之前存在匹配项,则 return 否则 return 什么都没有。
这里是 demo.
我的目标是 return 如果在 '->' 特殊字符之前找到匹配,否则 return 什么都没有。它不应该 return '->' 特殊字符之后的匹配项。
正则表达式:/()()(\[[^\]]+\])\s*(-[->])(.*)/g
// 在第三组中,实际结果将是 returned
例如数据:
[AAA] -> [BBB] -> [CCC] // 在这种情况下需要匹配 [AAA]
AAA -> [BBB] -> [CCC] // 在这种情况下不要 return [BBB],而是 return nothing as before special char '->', no matchng有吗
请帮我解决这个问题。提前致谢。
这是你想要的吗?
^\[[^\]]+\](?=\h*->)
解释:
^ # beginning of string
\[ # opening squarre bracket
[^\]]+ # 1 or more any character that is not closiing bracket
\] # closing bracket
(?= # start positive lookahead, make sure we have after:
\h* # 0 or more horizontal spaces
-> # literally ->
) # end lookahead
使用这个正则表达式
^\[(.*?)\] ->
并捕获第 1 组(在大括号内)。
我不完全理解这个问题,只是在此处复制一些猜测,这可能会让您更接近您要完成的目标:
^()()((\[[^\]]*\]))\s*->(.*)
Demo 1
()()(\[[^\]]+\])\s*->(\s*\[[^\]]+\]\s*->\s*\[[^\]]+\])
Demo 2
()()(\[[^\]\r\n]+\])\s*->\s*(\[[^\]\r\n]+\]\s*->\s*\[[^\]\r\n]+\])
Demo 3
const regex = /^()()((\[[^\]]*\]))\s*(->)(.*)/gm;
const str = `[AAA] -> [BBB] -> [CCC]
AAA -> [BBB] -> [CCC]`;
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}`);
});
}
正则表达式电路
jex.im 可视化正则表达式:
我是正则表达式的新手,一直在尝试匹配表达式直到出现特殊的 character/s。如果在特殊字符之前存在匹配项,则 return 否则 return 什么都没有。
这里是 demo.
我的目标是 return 如果在 '->' 特殊字符之前找到匹配,否则 return 什么都没有。它不应该 return '->' 特殊字符之后的匹配项。
正则表达式:/()()(\[[^\]]+\])\s*(-[->])(.*)/g
// 在第三组中,实际结果将是 returned
例如数据:
[AAA] -> [BBB] -> [CCC] // 在这种情况下需要匹配 [AAA]
AAA -> [BBB] -> [CCC] // 在这种情况下不要 return [BBB],而是 return nothing as before special char '->', no matchng有吗
请帮我解决这个问题。提前致谢。
这是你想要的吗?
^\[[^\]]+\](?=\h*->)
解释:
^ # beginning of string
\[ # opening squarre bracket
[^\]]+ # 1 or more any character that is not closiing bracket
\] # closing bracket
(?= # start positive lookahead, make sure we have after:
\h* # 0 or more horizontal spaces
-> # literally ->
) # end lookahead
使用这个正则表达式
^\[(.*?)\] ->
并捕获第 1 组(在大括号内)。
我不完全理解这个问题,只是在此处复制一些猜测,这可能会让您更接近您要完成的目标:
^()()((\[[^\]]*\]))\s*->(.*)
Demo 1
()()(\[[^\]]+\])\s*->(\s*\[[^\]]+\]\s*->\s*\[[^\]]+\])
Demo 2
()()(\[[^\]\r\n]+\])\s*->\s*(\[[^\]\r\n]+\]\s*->\s*\[[^\]\r\n]+\])
Demo 3
const regex = /^()()((\[[^\]]*\]))\s*(->)(.*)/gm;
const str = `[AAA] -> [BBB] -> [CCC]
AAA -> [BBB] -> [CCC]`;
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}`);
});
}
正则表达式电路
jex.im 可视化正则表达式: