Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a regex to match a string NOT at the end of a line?

Tags:

regex

ruby

The regex /abc$/ will match an abc that does appear at the end of the line. How do I do the inverse?

I want to match abc that isn't at the end of a line.

Furthermore, I'm going to be using the regex to replace strings, so I want to capture only abc, not anything after the string, so /abc.+$/ doesn't work, because it would replace not only abc but anything after abc too.

What is the correct regex to use?

like image 767
Tim Avatar asked May 06 '12 23:05

Tim


People also ask

Which regex matches the end of line?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.

What does '$' mean in regex?

Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.

How do you search for a regex pattern at the beginning of a string?

The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.

Which regex character would you use to indicate that a given string ends with the specified word?

If you only want a match at the absolute very end of the string, use \z (lowercase z instead of uppercase Z).


1 Answers

/abc(?!$)/ 

(?!$) is a negative lookahead. It will look for any match of abc that is not directly followed by a $ (end of line)

Tested against

  • abcddee (match)
  • dddeeeabc (no match)
  • adfassdfabcs (match)
  • fabcddee (match)

applying it to your case:

ruby-1.9.2-p290 :007 > "aslkdjfabcalskdfjaabcaabc".gsub(/abc(?!$)/, 'xyz')   => "aslkdjfxyzalskdfjaxyzaabc"  
like image 197
Benjamin Udink ten Cate Avatar answered Sep 22 '22 06:09

Benjamin Udink ten Cate