The Beginning and the End (of a Line)

Find and replace with regular expressions is pretty amazing, but one part of the previous regular expression is not quite right. The regular expression matches 'age=' and then some numbers. What if the author string also contained 'page=23'? Then our regular expression would match 'age=27' and 'page=23'. We could change our regular expression to be /(&age=)(\d+)/, but we would still have a problem: What if 'age' is at the beginning of the string and there is no preceding &? Fortunately, regular expressions have a way of identifying the beginning (and end) of a line. The beginning of a line is represented by a ^ (remember, the ^ has a different meaning inside brackets—regular expressions sure can be confusing), ...

Get Learning to Program now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.