Need to Trim Java String - java

I need help in trimming a string url.
Let's say the String is http://myurl.com/users/232222232/pageid
What i would like returned would be /232222232/pageid
Now the 'myurl.com' can change but the /users/ will always be the same.

I suggest you use substring and indexOf("/users/").
String url = "http://myurl.com/users/232222232/pageid";
String lastPart = url.substring(url.indexOf("/users/") + 6);
System.out.println(lastPart); // prints "/232222232/pageid"
A slightly more sophisticated variant would be to let the URL class parse the url for you:
URL url = new URL("http://myurl.com/users/232222232/pageid");
String lastPart = url.getPath().substring(6);
System.out.println(lastPart); // prints "/232222232/pageid"
And, a third approach, using regular expressions:
String url = "http://myurl.com/users/232222232/pageid";
String lastPart = url.replaceAll(".*/users", "");
System.out.println(lastPart); // prints "/232222232/pageid"

string.replaceAll(".*/users(/.*/.*)", "$1");

String rest = url.substring(url.indexOf("/users/") + 6);

You can use split(String regex,int limit) which will split the string around the pattern in regex at most limit times, so...
String url="http://myurl.com/users/232222232/pageid";
String[] parts=url.split("/users",1);
//parts={"http://myurl.com","/232222232/pageid"}
String rest=parts[1];
//rest="/232222232/pageid"
The limit is there to prevent strings like "http://myurl.com/users/232222232/users/pageid" giving answers like "/232222232".

You can use String.indexOf() and String.substring() in order to achieve this:
String pattern = "/users/";
String url = "http://myurl.com/users/232222232/pageid";
System.out.println(url.substring(url.indexOf(pattern)+pattern.length()-1);

Related

Using regular expressions to rename a string

In java, I want to rename a String so it always ends with ".mp4"
Suppose we have an encoded link, looking as follows:
String link = www.somehost.com/linkthatIneed.mp4?e=13974etc...
So, how do I rename the link String so it always ends with ".mp4"?
link = www.somehost.com/linkthatIneed.mp4 <--- that's what I need the final String to be.
Just get the string until the .mp4 part using the following regex:
^(.*\.mp4)
and the first captured group is what you want.
Demo: http://regex101.com/r/zQ6tO5
Another way to do this would be to split the string with ".mp4" as a split char and then add it again :)
Something like :
String splitChar = ".mp4";
String link = "www.somehost.com/linkthatIneed.mp4?e=13974etcrezkhjk"
String finalStr = link.split(splitChar)[0] + splitChar;
easy to do ^^
PS: I prefer to pass by regex but it ask for more knowledge about regex ^^
Well you can also do this:
Match the string with the below regex
\?.*
and replace it with empty string.
Demo: http://regex101.com/r/iV1cZ8
Try below code,
private String trimStringAfterOccurance(String link, String occuranceString) {
Integer occuranceIndex = link.indexOf(occuranceString);
String trimmedString = (String) link.subSequence(0, occuranceIndex + occuranceString.length() );
System.out.println(trimmedString);
return trimmedString;
}

Query regarding regular expression

hi I have a string like this:
String s = "#Path(\"/BankDBRestService/customerExist(String")\";
I want to make that string as
#Path("/BankDBRestService/customerExist")
I tried this:
String foo = s.replaceAll("[(](.*)", "");
i am getting output as
#Path
can anyone please provide me the reqular expression to make this work
Try this one :
String s = "#Path(\"/BankDBRestService/customerExist(String\")";
String res = s.replaceAll("[(]([a-zA-Z_])+", "");
System.out.println(res);
Output : #Path("/BankDBRestService/customerExist")
If your string is "#Path(\"/BankDBRestService/customerExist(String)\")" i.e. with closed parenthesis then use regex [(]([a-zA-Z_])+[)]
try this
String foo = s.replaceAll("(.*)\\(.*\\)", "$1");

More efficient way splitting than this?

Is there a more efficient way of splitting a string than this?
String input = "=example>";
String[] split = input.split("=");
String[] split1 = split[1].split(">");
String result = split1[0];
The result would be "example".
String result = input.replaceAll("[=>]", "");
Very simple regex!
To learn more, go to this link: here
Do you really need regex. You can do:
String result = input.substring(1, input.length()-1);
Otherwise if you really have a case for regex then use character class:
String result = input.replaceAll("[=>]", "");
If you just want to get example out of that do this:
input.substring(1, input.lastIndexOf(">"))
If the string of yours defenitely constant format use substring otherwise go fo regex
result = result.substring(1, result.length() - 1);
You can do it more elegant with RegEx groups:
String sourceString = "=example>";
// When matching, we can "mark" a part of the matched pattern with parentheses...
String patternString = "=(.*?)>";
Pattern p = Pattern.compile(patternString);
Matcher m = p.matcher(sourceString);
m.find();
// ... and access it later
String result = m.group(1);
You can try this regex: ".*?((?:[a-z][a-z]+))"
But it would be better when you use something like this:
String result = input.substring(1, input.length()-1);
try this
String result = input.replace("[\\W]", "")
You can try this too
String input = "=example>";
System.out.println(input.replaceAll("[^\\p{L}\\p{Nd}]", ""));
This will remove all non-words characters
Regex would do the job perfectly, but just to add something new for future solutions you also could use a third party lib such as Guava from Google, it adds a lot of functionalities to your project and the Splitter is really helpful to solve something like you have.

parsing a string using string tokenizer twice

I am getting input string as below from some procedure
service:jmx:t3://10.20.30.40:9031/jndi/weblogic.management.mbeanservers.runtime
I want to parse it in java and get out
t3
10.20.30.40
9031
into separate strings
I think I can use string tokenizer but I have to tokenize 2 times ?Any better way to handle this?
Use the JMXServiceUrl class. It will parse the URL for you. No need to battle with regex or String splits.
String url = "service:jmx:t3://10.20.30.40:9031/jndi/weblogic.management.mbeanservers.runtime";
JMXServiceURL jmxServiceURL = new JMXServiceURL(url);
System.out.println(jmxServiceURL.getHost());
System.out.println(jmxServiceURL.getPort());
System.out.println(jmxServiceURL.getProtocol());
Prints
10.20.30.40
9031
t3
If it's only a somehow composed String and you can ignorie performance, I would prefer a readable solution (more than regex ;-)) like this:
int pos_1 = input.indexOf("//");
String s1 = input.substring(0, pos_1);
String input_2 = input.substring(pos_1 + 2);
int pos_2 = input_2.indexOf(":");
String s2 = input_2.substring(0, pos_2);
...
Regex is a good approach. You should find the pattern for your string and group with parenthesis what you want. Maybe this could be enough for you:
service\\:jmx\\:(?<groupName01>[a-z0-9]+)\\://(?<groupName02>[0-9\\.]+)\\:(?<groupName03>[o-9]+)
See Java Regex
If you use java earlier from 7, do not use ?<groupName> in the pattern. It will be grouped by number.
Do a simple string split
String s = "service:jmx:t3://10.20.30.40:9031/jndi/weblogic.management.mbeanservers.runtime";
String tokens[] = s.split("[:/]");
System.out.println(tokens[2]);
System.out.println(tokens[5]);
System.out.println(tokens[6]);

Java replaceall ignore case and special characters

This is just an example code of the thing i try to accomplish.
String s = "hello(1234aA)something";
String replaceString = "(1234aa)";
String s2 = s.replaceAll("(i?)" + replaceString, "something");
The String s is going to be the same but can differ in case, thats why i use (i?) in replaceall.
How can i make regex ignore the special
Use quote(), it seems you've already figured out the ignore case, but you should use (?i), not (i?).
String s = "hello(1234aA)something";
String replaceString = "(?i)" + Pattern.quote("(1234aa)");
String s2 = s.replaceAll(replaceString, "something");
This should work.

Categories

Resources