0

I understand that ?! is to exclude a pattern, so for example a(?!b) means it will match "a" if "a" is not followed by "b". My question is, suppose I have a file with the following content:

a cat is a cat, a dog is a dog,

a bird is a bird.

How many times will the pattern a(?!.*b) match? Is it 0 times? since all "a"s are before the "b" in the last word "bird"?

3
  • 1
    I don't know much regex but this site is godly: regex101.com Commented Apr 17, 2015 at 1:25
  • see regex101.com/r/sI4wE1/1 . You could play with the regex in this site. Commented Apr 17, 2015 at 1:27
  • This site is awesome! thanks a lot! Commented Apr 17, 2015 at 1:29

1 Answer 1

1

It will match for every a. The pattern a(?!b) means it will match any a not immediately followed by b. cab wouldn't match, but a bird will.

EDIT

With your new pattern a(?!.*b), no match if all of your text is on the same line. The .* does not match linebreaks, so:

A cat is a cat, a dog is a dog

A bird is a bird

This would have matches for every a of the first line.

Sign up to request clarification or add additional context in comments.

6 Comments

No problem, I will edit my answer, but your assumption is right; no match except linebreaks. See above
.* matches any character (except newline). I didn't know * couldn't match linebreaks. Hence the confusion. :D Thank you for your explanation!
* can, . can't ;) If you want to check everything, including newlines/linebreaks, I believe you would use [.\s]*. My pleasure! Have fun with regexes :)
@Docteur, [.\s] matches a literal dot or a whitespace character. If you want to match any character including newlines, use the dot in Singleline/DOTALL mode. One way to do that is with an inline modifier: (?s)a(?!.*b)
Yeah, that works, too. That idiom comes from JavaScript and other ECMAScript implementations, which don't have a dot-matches-everything mode, but it works in all regex flavors.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.