Lolly
Lolly

Reputation: 36432

Java regex pattern for a string

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

Answers (4)

Srihari
Srihari

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

user1596371
user1596371

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

jlordo
jlordo

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

Ryan Stewart
Ryan Stewart

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

Related Questions