More efficient way splitting than this? - java

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.

Related

Regex Redirect URL excludes token

I'm trying to create a redirect URL for my client. We have a service that you specify "fromUrl" -> "toUrl" that is using a java regex Matcher. But I can't get it work to include the token in when it converts it. For example:
/fromurl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf
Should be:
/tourl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf
but it excludes the token so the result I get is:
/fromurl/login/
/tourl/login/
I tried various regex patterns like: " ?.* and [%5E//?]+)/([^/?]+)/(?.*)?$ and (/*) etc" but no one seems to work.
I'm not that familiar with regex. How can I solve this?
This can be easily done using simple string replace but if you insist on using regular expressions:
Pattern p = Pattern.compile("fromurl");
String originalUrlAsString = "/fromurl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf ";
String newRedirectedUrlAsString = p.matcher(originalUrlAsString).replaceAll("tourl");
System.out.println(newRedirectedUrlAsString);
If I understand you correctly you need something like this?
String from = "/my/old/url/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
String to = from.replaceAll("\\/(.*)\\/", "/my/new/url/");
System.out.println(to); // /my/new/url/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
This will replace everything between the first and the last forward slash.
Can you detail more exactly what the original expression is like? This is necessary because the regular expression is based on it.
Assuming that the first occurrence of fromurl should simply be replaced with the following code:
String from = "/fromurl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
String to = from.replaceFirst("fromurl", "tourl");
But if it is necessary to use more complex rules to determine the substring to replace, you can use:
String from = "/fromurl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
String to = "";
String regularExpresion = "(<<pre>>)(fromurl)(<<pos>>)";
Pattern pattern = Pattern.compile(regularExpresion);
Matcher matcher = pattern.matcher(from);
if (matcher.matches()) {
to = from.replaceAll(regularExpresion, "$1tourl$3");
}
NOTE: pre and pos targets are referencial because I don't know the real expresion of the url
NOTE 2: $1 and $3 refer to the first and the third group
Although existing answers should solve the issue and some are similar, maybe below solution would be of help, with quite an easy regex being used (assuming you get input of same format as your example):
private static String replaceUrl(String inputUrl){
String regex = "/.*(/login\\?token=.*)";
String toUrl = "/tourl";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(inputUrl);
if (matcher.find()) {
return toUrl + matcher.group(1);
} else
return null;
}
You can write a test if it works for other expected inputs/outputs if you want to change format and adjust regex:
String inputUrl = "/fromurl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
String expectedUrl = "/tourl/login?token=7c8Q8grW5f2Kz7RP1%2FWsqpVB%2FEluVOGfXQdW4I0v82siR2Ism1D8VCvEmKJr%2BKhHhicwPey0uIiTxN049Be8TNsypf";
if (expectedUrl.equals(replaceUrl(inputUrl))){
System.out.println("Success");
}

Parse string value from URL

I have a string (which is an URL) in this pattern https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg
now I want to clip it to this
media/93939393hhs8.jpeg
I want to remove all the characters before the second last slash /.
i'm a newbie in java but in swift (iOS) this is how we do this:
if let url = NSURL(string:"https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg"), pathComponents = url.pathComponents {
let trimmedString = pathComponents.suffix(2).joinWithSeparator("/")
print(trimmedString) // "output = media/93939393hhs8.jpeg"
}
Basically, I'm removing everything from this Url expect of last 2 item and then.
I'm joining those 2 items using /.
String ret = url.substring(url.indexof("media"),url.indexof("jpg"))
Are you familiar with Regex? Try to use this Regex (explained in the link) that captures the last 2 items separated with /:
.*?\/([^\/]+?\/[^\/]+?$)
Here is the example in Java (don't forget the escaping with \\:
Pattern p = Pattern.compile("^.*?\\/([^\\/]+?\\/[^\\/]+?$)");
Matcher m = p.matcher(string);
if (m.find()) {
System.out.println(m.group(1));
}
Alternatively there is the split(..) function, however I recommend you the way above. (Finally concatenate separated strings correctly with StringBuilder).
String part[] = string.split("/");
int l = part.length;
StringBuilder sb = new StringBuilder();
String result = sb.append(part[l-2]).append("/").append(part[l-1]).toString();
Both giving the same result: media/93939393hhs8.jpeg
string result=url.substring(url.substring(0,url.lastIndexOf('/')).lastIndexOf('/'));
or
Use Split and add last 2 items
string[] arr=url.split("/");
string result= arr[arr.length-2]+"/"+arr[arr.length-1]
public static String parseUrl(String str) {
return (str.lastIndexOf("/") > 0) ? str.substring(1+(str.substring(0,str.lastIndexOf("/")).lastIndexOf("/"))) : str;
}

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]);

Split a string in Java if it contains digit - but include digit in result?

I'm looking to split a string using Java if it contains a digit or underscore - but I want to include the digit in the result - is this possible?
Eg.
"Linux_version"
"Linux3.1.2.x"
I want to split strings like these to get either "version" if it contains an underscore, or the digits to the end of the string if it contains a digit - e.g. from the second string above - I want "3.1.2.x"
Any help is much appreciated!
expectedString = yourString.replaceAll("^[^_0-9]+_?","");
If you just want to remove Linux or Linux_, try this:
expectedString = yourString.replaceAll("(?i)^linux_?","")
This regex replace will do it:
input.replaceAll("^.*?((?<=_)|(?=\\d))", "");
String input = "Linux_version";
//String input = "Linux3.1.2.x";
String result = null;
Pattern p = Pattern.compile("_(.*)|(\\d.*)");
Matcher m = p.matcher();
if (m.find()){
if (m.group(1) != null){
result = m.group(1); //"version"
} else if (m.group(2) != null){
result = m.group(2); //"3.1.2.x"
}
}
Can't help you with java code but I think you can use the following regex pattern;
(_|[0-9])+[.a-zA-Z0-9]+

Need to Trim Java String

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);

Categories

Resources