Regex - everything up to an optional pattern, or just everything

Viewed 46

I have the following text:
This is a sequence of nothing. This is another

I'm trying to write a regex that can get everything until a dot followed by space (\.\s), but if this dot followed by a space is not present in the string, then i want everything.

Example:

This is a sequence of nothing. This is another
This is a sequence of nothing

This is a sequence of nothing this is another
This is a sequence of nothing this is another


I was trying this one, but even when the string has a dot followed by a space it gets everything:
This is a sequence (.*)(\.\s)?

PS: I'm applying this regex in python

2 Answers

You can try this regex:

This is a sequence ((?:(?!\.\s).)*)
  • ((?:...)*) a group of a non-capture group, repeats any times.
  • (?!\.\s). any character with a negative look ahead, the next two characters will never form a fullstop and a space

See the test cases

Using python:

import re

text = '''
This is a sequence of nothing. This is another
This is a sequence of nothing this is another
'''

result = re.findall(r'This is a sequence ((?:(?!\.\s).)*)', text)
print(result) # ['of nothing', 'of nothing this is another']

Assuming you want to exclude the dot into your result, you could try:

^This is a sequence (.*?)(?:\. |$)

See an online demo

  • ^ - Start line anchor.
  • This is a sequence - Literally "This is a sequence ".
  • (.*?) - A capture group holding 0+ (lazy quantifier) characters upto;
  • (?:\. |$) - A non-capture group with either a literal dot followed by a literal space or the end line anchor.

import re
text =  "This is a sequence of nothing. This is another"
result = re.findall(r'^This is a sequence (.*?)(?:\. |$)', text)[0]
print(result) # of nothing
Related