goldisfine
goldisfine

Reputation: 4850

How to use ^ and $ to parse simple expression?

How do I use the ^ and $ symbols to parse only /blog/articles in the following?

I've created ex3.txt that contains this:

/blog/article/1 
/blog/articles 
/blog 
/admin/blog/articles

and the regex:

^/blog/articles$

doesn't appear to work, as in when I type it using 'regetron' (see learning regex the hard way) there is no output on the next line.

This is my exact procedure:

  1. At command line in the correct directory, I type: regetron ex3.txt. ex3.txt contains one line with the following:

    /blog/article/1 /blog/articles /blog /admin/blog/articles

although I have tried it with newlines between entries.

  1. I type in ^/blog/article/[0-9]$ and nothing is returned on the next line.

  2. I try the first solution posted,^\/blog\/articles$ and nothing is returned.

Thanks in advance SOers!

Upvotes: 5

Views: 150

Answers (2)

Eric
Eric

Reputation: 6016

Based on your update, it sounds like ^ and $ might not be the right operators for you. Those match the beginning and end of a line respectively. If you have multiple strings that you want to match on the same line, then you'll need something more like this:

(?:^|\s)(\/blog\/articles)(?:$|\s)

What this does:

(?:^|\s)            Matches, but does not capture (?:), a line start (^) OR (|) a whitespace (\s)
(\/blog\/articles)  Matches and captures /blog/articles.
(?:$|\s)            Matches, but does not capture (?:), a line end ($) OR (|) a whitespace (\s)

This will work for both cases, but be aware that it will match (but will not capture) up to a single whitespace before and after /blog/articles.

Upvotes: 1

David Sherret
David Sherret

Reputation: 106900

Change your regex to:

^\/blog\/articles$

You need to escape your slashes.

Also, ensure there are no trailing spaces on the end of each line in your ex3.txt file.

Upvotes: 5

Related Questions