I am a newbie to regexp and was trying to match the expression until a special character/s. If the matches exist before the special character then return it otherwise return nothing.
Here is the demo .
My goal is to return the match if found before the '->' special character otherwise return nothing. It should not return the matches after the '->' special char.
Regexp: /()()(\[[^\]]+\])\s*(-[->])(.*)/g
// In third group actual result will be returned
For example data:
[AAA] -> [BBB] -> [CCC] // In this case needs to match [AAA]
AAA -> [BBB] -> [CCC] // In this case do not return [BBB], instead return nothing as before special char '->', no matchng is there.
Please help me with this. Thanks in advance.
Is this what you want?
^\[[^\]]+\](?=\h*->)
Explanation:
^ # 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
I don't fully understand the problem, just copying a few guessworks in here, that might get you closer to what you're trying to accomplish:
^()()((\[[^\]]*\]))\s*->(.*)
()()(\[[^\]]+\])\s*->(\s*\[[^\]]+\]\s*->\s*\[[^\]]+\])
()()(\[[^\]\r\n]+\])\s*->\s*(\[[^\]\r\n]+\]\s*->\s*\[[^\]\r\n]+\])
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 visualizes regular expressions:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.