0

i'm trying to create a regExp for this strings in java :

key:value
key:"value" 
key:'value' 
key : value  
key :"value 123" 
key: 'value 123'

every condition can be in a single line :

key:value key : value key : "value 123"

i've to match each of them, capturing key and value, trimmed and without quotes.

unfortunately java does not support conditionals in regex.

Can someone help me?

Thanks in advance.

5
  • 1
    Dont understand your question. Commented Mar 28, 2013 at 10:09
  • you want the the strings to become in a single line ? (because I did not understand what you aree realy looking for) Commented Mar 28, 2013 at 10:09
  • Can you please supply an example of INPUT and the desired OUTPUT that match your needs? Your question is not that much clear. Commented Mar 28, 2013 at 10:11
  • My matcher must have multiple find with 2 group each, key and value. Commented Mar 28, 2013 at 10:23
  • Not working sample : ([\w\d]+)\s*:\s*(.+) because if i have multiple find on a single line it matches all the line Commented Mar 28, 2013 at 10:25

3 Answers 3

1

This should suit your needs (demo):

(\w+)\s*:\s*((?:.(?!\w+\s*(?<!\\):))*)

The first group contains the key, the second one the value.

I added a way to manage the nested : in the values: just escape them with \.

You'll still have to trim the results though.

Sign up to request clarification or add additional context in comments.

1 Comment

maybe adding \s* ? (\\w+)\\s*:\\s*((?:.(?!\\w+\\s*:))*)
1

This pattern should satisfy those requirements:

(\w+)( *):( *)(\w+|(["'])([\w\s]+)\5)

2 Comments

it does not match key:"value or key:value'
Hmmm. Fixed a mistake in it. But I'm not sure what pair it should find for the value you've commented. The regex I have now finds the second one and ignores the first. Is that what you want? I am not sure whether you're asking about the nested key value pair or the mismatched quotes.
0

You can use following regex:

/(\w+)\s*:\s*(((['"]).+?\4)|\w+)/

Group # 1 will be your key and Group # 2 will be value.

Live Demo: http://www.rubular.com/r/IPqtdneBeW

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.