0

sorry if this is a duplicate but i couldnt find anything close.

i want to check recursively a string for the following pattern

[a-z0-9][:][a-z0-9][&][a-z0-9][:][a-z0-9]...

example

foo:bar&foo:bar1&foo:bar&foo:111&bar:2A2... 

is it possible with regex and if so anyone can show me a regex expression for this?

If there is a efficient java method for this, it would be also good.

2
  • So you have to check if there are only letter and numbers in string and 1 : ? Commented Jul 31, 2015 at 7:33
  • 1
    Show us the expected result. Commented Jul 31, 2015 at 7:36

3 Answers 3

2

Assuming that you want to match the whole string:

(\w+:\w+(?:&\w+:\w+)*)

See a demo.


Regular expression visualization

Debuggex Demo

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

6 Comments

does "(..)+" means repeating?
+ means match one or more times ? means match zero or one time.
@AvinashRaj It depends on what exactly is supposed to be matched, but you may be right. I updated the answer.
You should always use the second version. The first version, if used with String.matches in Java, which asserts that the whole string has to match the regex, will match foo:barfoo:bar1 regex101.com/r/fN7uX4/1
Another thing is that \w also matches capital letters and _, which is not in the original expression.
|
2

Just put the pattern inside a group with a preceding & and then make it to repeat zero or more times.

^[a-z0-9]+:[a-z0-9]+(?:&[a-z0-9]+:[a-z0-9]+)*$

Anchors won't be needed if you use matches method.

DEMO

Comments

1

If you want to match value:value& as a sole element multiple times,

(([a-z0-9]+:)([a-z0-9]+&))+

NOTE : It won't match value:value&value:,value&value&value: etc.

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.