Regex for key-value pairs, including unsolicited spaces

I need a regular expression to parse key-value pairs from a properties file to write them to the database. The application is written in java. Since I need to store information about comment lines and empty lines, properties.load does not work for me

The key is everything until the first appearance of an unnamed space or equal sign (including shielded spaces). The value is everything to the end of the line, but it can also be empty.

It should correspond to the following cases:

  • key = value
  • key value
  • key = value
  • key
  • Key value
  • key \ key \ key = value
  • key \ key \ key value

I tried the following regular expression, but it does not separate the last two cases correctly:

^(\\\s|[^\s=]+)+[\s|=](.*)?$

For the last two examples, I get Rubular:

1. key\
2. key\ key value

instead

1. key\ key\ key
2. value

, .

!

+5
2

lookbehind (?<!\\\\)\s

^((.*?)((?<!\\\\)\\s|=)(.*?)|(\\w+))$

(.*?)             Match everything non greedy up to the next match
((?<!\\\\)\\s|=)  Match witespace not preceded by \\
(.*?)             Again match everything non greedy up to the next match
|\\w+             Or match strings with no whitespace - this captures case 3 with no value

, http://www.cis.upenn.edu/~matuszek/General/RegexTester/regex-tester.html

+2

(, , Java):

^(\\\s|[^\s=])+(.*)$
0

All Articles