Jump to content

What is the purpose of the begin and end ^ and $ characters, when should I use them and what do they do?


EasyLearner
Go to solution Solved by gizmola,

Recommended Posts

Hi all !

I am new to regular expressions but been using PHP for a while, so I am experimenting with preg_match().

I understand that rexex patterns need to be delimited ie / . . . pattern . . . / but I notice that some expressions also have a ^ and $ which apparently denotes beginning and end ie 

/^ . . .  pattern . . . $/ however some expressions seem to work with or without the start - end ^ - $ characters.

So, please, what are they for, when should I use them and when should I not - or are the 'optional' - what do they do?

Thanks guys

Link to comment
Share on other sites

  • Solution

If you are looking for -- exactly, a line that starts ... then has something you want to match, followed exactly by the end of a line, then you may want to use those anchors.  

Regex is integrated into a lot of different languages and subsystems, for a number of different purposes.  For example, it might be that your use case is to find, within a bunch of lines of text, a particular pattern like a phone number or a url.  

Another use case, might be entirely different, as in the case of a password which must meet certain criteria.  In the case of a password, you would want an exact match, including the start and end anchors, whereas, if you're looking for a phone number or a url within a bunch of other text (perhaps in a forum like this one) then you certainly would not want the match to only be made including the start and end line anchors.  

In some subsystems (apache mod_rewrite for example) the context of the data available to be evaluated with regex, already assumes start and end anchors, and actually trying to apply them won't work, so that might lead to some confusion, when rewrites don't work the way you expect.

Link to comment
Share on other sites

  • 2 weeks later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.