Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ^ and $ to parse simple expression?

Tags:

python

regex

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!

like image 965
goldisfine Avatar asked Jul 15 '13 16:07

goldisfine


People also ask

What is parsing an expression?

Parsing is the process of analysing a string of symbols, expressed in natural or computer languages that will accord formal grammar. Expression Parsing in Data Structure means the evaluation of arithmetic and logical expressions.

What is parsing explain with an example?

In linguistics, to parse means to break down a sentence into its component parts so that the meaning of the sentence can be understood. Sometimes parsing is done with the help of tools such as sentence diagrams (visual representations of syntactical constructions).

How do you parse an expression in Java?

Here's how an arithmetic expression is parsed. A pointer is started at the left and is iterated to look at each character. It can be either a number(always a single-digit character between 0 and 9) or an operator (the characters +, -, *, and /). If the character is a number, it is pushed onto the stack.


2 Answers

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.

like image 169
David Sherret Avatar answered Oct 16 '22 14:10

David Sherret


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.

like image 41
Eric Avatar answered Oct 16 '22 14:10

Eric