0

I want to use regular expressions to search for a line consisting of one single word. Say the word was apple, and I am searching:

apple
banana
apple pear banana
apple banana
pear apple
pear

I only want it to match "apple". I do not want to match apple just at the beginning of the line, but when the line is equal to "apple".

Edit: for those asking why I'm using regular expressions, I need to check for the word case-insensitively, thus I'm using (?i)apple

Edit2: I'm modifying the title to reflect that this can be used not just for a specific word, but anytime we are looking for the entire contents of a line, rather than just matching lines that contain the expression

Joel M.
  • 248
  • 1
  • 2
  • 12
  • What are you trying to achieve? – Wiktor Stribiżew Aug 31 '17 at 19:12
  • I'm trying to achieve what I asked in the question - to match a single word line only. If I do '(?i)apple' it will match all lines that contain "apple" – Joel M. Aug 31 '17 at 19:14
  • I've discovered a solution - I'm going to answer my own question since I haven't been able to find another answer. – Joel M. Aug 31 '17 at 19:16
  • Not a duplicate of that - the solution to that question will match all lines with words after "apple". – Joel M. Aug 31 '17 at 19:19
  • And I don't understand the downvotes - is the question not clear? – Joel M. Aug 31 '17 at 19:19
  • Does this answer your question? [How to make grep only match if the entire line matches?](https://stackoverflow.com/questions/4709912/how-to-make-grep-only-match-if-the-entire-line-matches) – tripleee Feb 20 '20 at 13:53

2 Answers2

2

Use anchors:

^apple$

Or compare them via string functions as there do not seem to be changing parts which would make regular expression kind of a must.

Jan
  • 42,290
  • 8
  • 54
  • 79
0

I found the solution after more experimentation - the answer is to search for the word at both the beginning (^) and end ($) of the line:

'^apple$'
Joel M.
  • 248
  • 1
  • 2
  • 12
  • A much better solution is to string compare it `== "apple"` Otherwise, for multi-line string, the anchors only match the beginning and end of string. For that you'd need `(?m)^apple$` which would find it on a line by itself. But, it still doesn't tell you much about it. –  Aug 31 '17 at 19:38