-1

I am trying to match a sentence that starts with "hello" and ends with "bye". For example, "hello something bye" should result in a match.

I tried using the regular expression ^hello|[a-z]|bye$, but it detects everything. I have also tried googling, but I couldn't find a solution for this exact case.

Andreas Violaris
  • 2,465
  • 5
  • 13
  • 26

3 Answers3

1
^hello\b.*\bbye$

Explanation:

  • ^ matches the start of the string (sentence)

  • hello matches the literal word "hello"

  • .* matches any character (except for newline) zero or more times

  • \b matches a word boundary (to ensure that "bye" is a whole word, not just a substring)

  • bye matches the literal word "bye"

  • $ matches the end of the string (sentence)

ABR
  • 134
  • 5
1

Generally speaking, you could use the regex pattern ^\w+|\w+$, which would only match words at the beginning or end. Assuming your actual language be Python, we can try:

inp = "hello something bye"
matches = re.findall(r'^\w+|\w+$', inp)
print(matches)  # ['hello', 'bye']
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Based on your comments, it seems that you want to match all instances of the specified pattern. In order to achieve this, you can use something like this:

import re

text = "irrelevant sentence hello first sentence bye irrelevant sentence hello second sentence bye " \
       "irrelevant sentence hello third sentence bye irrelevant sentence"

regex = r"(?:^|\s)(hello\s.*?bye)(?=\s|$)"

matches = re.findall(regex, text)

if matches:
    print("Matches found:", matches)
else:
    print("Matches not found.")

Output:

Matches found: ['hello first sentence bye', 'hello second sentence bye', 'hello third sentence bye']
Andreas Violaris
  • 2,465
  • 5
  • 13
  • 26