3

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.

0

4 Answers 4

2

Matches word characters (letters, digits, and underscore _)... as many as it can

Pattern.compile( "(\w+)->(\w+)" );
Sign up to request clarification or add additional context in comments.

2 Comments

Good if the key and value doesn't have space between them.
Best option if keys cannot contain dashes.
1

Try

Pattern p = Pattern.compile("([^\s]+?)->([^\s]+)");

(did not test in Java).

1 Comment

^\s can be replaced by \S, and the square brackets are not needed. This leaves you with the much shorter "(\S+?)->(\S+)" :)
0

The Part [^(->)]* of your regexp definitely is not what you want. It matches a sequence of characters, not containing any of the characters (, -, > and ).

1 Comment

I need this one to avoid ->->->
0

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.

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.