Skip to Content
Regular Expressions Cookbook
book

Regular Expressions Cookbook

by Jan Goyvaerts, Steven Levithan
May 2009
Intermediate to advanced
510 pages
15h
English
O'Reilly Media, Inc.
Content preview from Regular Expressions Cookbook

8.14. Match INI Name-Value Pairs

Problem

You want to match INI parameter name-value pairs (e.g., Item1=Value1), separating each match into two parts using capturing groups. Backreference 1 should contain the parameter name (Item1), and backreference 2 should contain the value (Value1).

Solution

Here’s the regular expression to get the job done (the second is shown with free-spacing mode):

^([^=;\r\n]+)=([^;\r\n]*)
Regex options: ^ and $ match at line breaks
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby
^               # Start of a line
( [^=;\r\n]+ )  # Capture the name to backreference 1
=               # Name-value delimiter
( [^;\r\n]* )   # Capture the value to backreference 2
Regex options: ^ and $ match at line breaks, free-spacing
Regex flavors: .NET, Java, PCRE, Perl, Python, Ruby

Discussion

Like the other INI recipes in this chapter, we’re working with pretty straightforward ingredients here. The regex starts with ^, to match the position at the start of a line (make sure the “^ and $ match at line breaks” option is enabled). This is important because without the assurance that matches start at the beginning of a line, you could match part of a commented-out line.

Next, the regex uses a capturing group that contains a negated character class ([^=;\r\n]) followed by the one-or-more quantifier (+) to match the name of the parameter and remember it as backreference 1. The negated class matches any character except the following four: equals sign, semicolon, carriage return (\r), and line feed ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Regular Expressions Cookbook, 2nd Edition

Regular Expressions Cookbook, 2nd Edition

Jan Goyvaerts, Steven Levithan

Publisher Resources

ISBN: 9780596802837Catalog PageErrata