ntonzz
ntonzz

Reputation: 97

regex needed which matches for two sample string

I have two input strings :

this-is-a-sample-string-%7b3DES%7dFPvKTjGHUA3lD9Us70rfjQ==?Id=113690_2&Index=0&Referrer=IC

this-is-a-sample-string-%7b3DES%7dFPvKTjGHUA3lD9Us70rfjQ==

What I want is only the %7b3DES%7dFPvKTjGHUA3lD9Us70rfjQ== from both of the sample strings.

I tried by using the regex [a-zA-Z-]+-(.*) which works fine for the second input string.

String inputString = "this-is-a-sample-string-%7b3DES%7dFPvKTjGHUA3lD9Us70rfjQ==";
String regexString = "[a-zA-Z-]+-(.*)";

Pattern pattern = Pattern.compile(regexString);
Matcher matcher = pattern.matcher(inputString);

if(matcher.matches()) {
    System.out.println("--->" + matcher.group(1) + "<---");
} else {
    System.out.println("nope");
}

Upvotes: 1

Views: 96

Answers (1)

midgetspy
midgetspy

Reputation: 689

The following patterns match the desired group with the limited information and examples provided:

-([^-?]*)(?:\?|$)

.*-(.*?)(?:\?|$)

The first will match a hyphen then group all the characters up to either the ? or the end of the string.

The second matches as many characters and hyphens as possible followed by the smallest string to either the next question mark or the end of the string.

There are dozens of ways of writing something that will match this text though so I'm kinda just guessing if this is what you wanted. If this is not what you're after please elaborate on what exactly you're trying to accomplish.

Upvotes: 1

Related Questions