Domanda

I am looking for regex with capture group where question mark (?) can be present in my input string. If it is not present it returns the input string as it is, but if ? is present the return the string before the first occurrence of ?.

My input can be in following format

Pattern 1
abc.txt // result should be abc.txt
Pattern 2
abc.txt?param1=qwerty.controller&param2=xsd.txt // result should be abc.txt

I tried below

Matcher matcher = Pattern.compile("(.*?)\\?").matcher(str1);
String group1 = "";
if (matcher.find()) {
    group1 = matcher.group();
}

With this I am able to capture expected result for pattern 2, but I am not sure how to modify it so that I can capture expected result for both pattern 1 and pattern 2.

Update:- I know if group1 is empty string, i can make out that input string does not contain any ? and input string is the expected output here. But i am looking for if i can capture both patterns with single regex ?

È stato utile?

Soluzione

You could make use of a negated class like this:

^[^?]+

regex101 demo

^ first makes sure the match starts at the beginning.

[^?]+ matches all non-? characters (if there are none, it will match till the end).

Altri suggerimenti

Replace the first ? and everything after it (if it exists):

str = str.replaceAll("\\?.*", "");

One way is to remove everything from your string starting with the first question mark, like this:

String res = orig.replaceAll("[?].*$", "");

If there's no question mark, the expression will match nothing, so you would get the original string. Otherwise, the expression would match everything starting from the question mark, so replaceAll will delete it, because the replacement string is empty.

String orig = "abc.txt?param1=qwerty.controller&param2=xs?d.txt";
String res = orig.replaceAll("[?].*$", "");
System.out.println(res);
orig = "hello world";
res = orig.replaceAll("[?].*$", "");
System.out.println(res);

This prints

abc.txt
hello world

Link to a demo on ideone.

EDIT : I would like to capture both with a single regex

You can use "^[^?]*" for your regex. ^ anchors to the beginning, while [^?] captures everything - either up to the end of the string, or up to the first question mark. Either way, the question mark would be left out.

Here is the code:

String[] strings = new String[] {"abc.txt?param1=qwerty.controller&param2=xs?d.txt", "Hello, world!", "a?b"};
for (String str1 : strings) {
    Matcher matcher = Pattern.compile("^[^?]*").matcher(str1);
    String group1 = "";
    if (matcher.find()) {
         group1 = matcher.group();
    }
    System.out.println(group1);
}

Second demo on ideone.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top