0

I'm have a string: "abcde" When I want to take string after is c: /.*(?=c)/ => output fine: "ab" When I want to take string that behind without c /.*(?!c)/ => expect: no match But regex return match full string. Please explain for me, i understand. Sorry for my english not good. Thanks.

An Nguyễn
  • 19
  • 1
  • 4
  • `.*` in is greedy, so it will consume as many characters as possible, in this case to the end of the string. Then `(?!c)` ensures that that is not followed by the character `c`, which is satisfied, so the entire string is matched. Note that if the string were `abcdcecf`, `/.*(?=c)/` would match `abcdce` whereas `/.*?(?=c)/` would match `ab`, `?` in `.*?` making the match non-greedy. – Cary Swoveland Mar 29 '20 at 18:21
  • [Explanation](https://regex101.com/r/5jEKXk/1), [visualization](https://regex101.com/r/5jEKXk/1/debugger). – Wiktor Stribiżew Mar 29 '20 at 22:14
  • Thanks reply. Lookaround is still difficult for me. I don't understand why sometimes lookahead (take str before) is placed at the beginning of the pattern, and lookbehind (take str after) is sometimes placed at the end of the pattern, So if it matches, it takes the empty character?. I guess that it involves sections like: zero-width, backtrack? Example: `/^((?!c).)*$/` "abcdef abdefg " I could not understand why it matched the bottom line I debugged it at: https://regex101.com/r/SjDrHE/1 I find that the number of match steps required is 53 and I don't really understand – An Nguyễn Mar 30 '20 at 04:18

0 Answers0