Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex matching beginning AND end strings

Tags:

regex

This seems like it should be trivial, but I'm not so good with regular expressions, and this doesn't seem to be easy to Google.

I need a regex that starts with the string 'dbo.' and ends with the string '_fn'

So far as I am concerned, I don't care what characters are in between these two strings, so long as the beginning and end are correct.

This is to match functions in a SQL server database.

For example:

dbo.functionName_fn - Match  dbo._fn_functionName - No Match  dbo.functionName_fn_blah - No Match 
like image 640
bopapa_1979 Avatar asked Sep 11 '11 22:09

bopapa_1979


People also ask

What matches the start and end of the string?

They are called “anchors”. The caret ^ matches at the beginning of the text, and the dollar $ – at the end. The pattern ^Mary means: “string start and then Mary”.

How do you start and end a regular expression?

To match the start or the end of a line, we use the following anchors: Caret (^) matches the position before the first character in the string. Dollar ($) matches the position right after the last character in the string.

How do you define the regex string pattern that will match the end of the line?

The end of the line is expressed with the dollar sign ($) in the regex. The end of the line will be put at the end of the regex pattern and the required pattern will be specified before the $ sign. The end of the line character is generally used to “line ends with a word, character, characters set, number, etc.”.


2 Answers

If you're searching for hits within a larger text, you don't want to use ^ and $ as some other responders have said; those match the beginning and end of the text. Try this instead:

\bdbo\.\w+_fn\b 

\b is a word boundary: it matches a position that is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one. This regex will find what you're looking for in any of these strings:

dbo.functionName_fn foo dbo.functionName_fn bar (dbo.functionName_fn) 

...but not in this one:

foodbo.functionName_fnbar 

\w+ matches one or more "word characters" (letters, digits, or _). If you need something more inclusive, you can try \S+ (one or more non-whitespace characters) or .+? (one or more of any characters except linefeeds, non-greedily). The non-greedy +? prevents it from accidentally matching something like dbo.func1_fn dbo.func2_fn as if it were just one hit.

like image 172
Alan Moore Avatar answered Sep 20 '22 18:09

Alan Moore


^dbo\..*_fn$ 

This should work you.

like image 27
Daniel A. White Avatar answered Sep 20 '22 18:09

Daniel A. White