Reputation: 2040
I have a string I need to get array (2 - dim) of key->value pairs.
A "match" is when there is a -> between 2 words, mo spaces before and after ->
For example input string:
skip_me key1->value1 key2->value2 skip_me_2 key3->value3 skip_me_3 skip_me -> also
The result should be array:
key1,value1
key2,value2
key3,value3
This is my code:
Pattern p = Pattern.compile( "\\s*([^(->)]+)->([^(->)]+)\\s*" );
Matcher m = p.matcher("skip_me key1->value1 key2->value2 skip_me_2 key3->value3 skip_me_3");
while( m.find() ) {
System.out.println( "Key:" + m.group(1) + "Value:" + m.group(2) );
}
My regex is wrong. Please assist.
Upvotes: 3
Views: 3953
Reputation: 3373
I think you might use:
Pattern.compile( "\\s*(([^\\s]+)(?=->))->((?<=->)([^\\s]+))\\s*" );
It uses positive lookahead and positive lookbehind to match everything before and after ->
.
Not tested in Java, only in Eclipse Regex Util based on your sample string.
Upvotes: 0
Reputation: 4938
The Part [^(->)]*
of your regexp definitely is not what you want. It matches a sequence of characters, not containing any of the characters (
, -
, >
and )
.
Upvotes: 0
Reputation: 27943
Matches word characters (letters, digits, and underscore _
)... as many as it can
Pattern.compile( "(\w+)->(\w+)" );
Upvotes: 2
Reputation: 32296
Try
Pattern p = Pattern.compile("([^\s]+?)->([^\s]+)");
(did not test in Java).
Upvotes: 1