Reputation: 36432
I am new to regex
. I am looking for regular expression which matches following pattern and extract the string,
key1=test1
key2="test1" // which will extract test1 stripping quotes
key3=New test
key4=New" "test // which will extract New" "test - as it is if the quotes come in between
I tried with \\s*(\\S+)\\s*=\\s*(\\S+*+)
, but not sure how to include quotes if present. Any help will be really appreciated.
Upvotes: 1
Views: 158
Reputation: 766
For Regex, if you want to include "
in your regex, simply escape it using \\"
. Whatever you are trying to achieve, test directly first at http://www.regexpal.com/
Upvotes: 0
Reputation:
You could use ^([^=]+)=("([^"]*)"|([^"].*))$
, but the answer will show up in the third or fourth group depending on if the value was quoted or not so you'd need to check both and pull whichever one was not null.
Upvotes: 0
Reputation: 37833
Here's a solution without regex to avoid problems with nested quotes:
String extractValue(String input) {
// check if '=' is present here...
String[] pair = input.split("=", 2);
String value = pair[1];
if (value.startsWith("\"") && value.endsWith("\"")) {
return value.substring(1, value.length() - 1);
}
return value;
}
Basically this is not without regex, because of the use of split()
, but it's not using regex the way you were planning to use it.
Upvotes: 2
Reputation: 128909
A simple solution would be to just load it as a Properties, which will do exactly the parsing you're looking for. Otherwise, just read each line and split the string at the first "=".
Upvotes: 2