split string and get the value using regex from a complicated string - java

I have a string like this {"product_tags":"yin_yang,yin yang"}.
what I want to do is just avoid everything else other than yin yang. There is two strings but I just want the first one.
Note that in some cases even if the second string is not available I want to get the same result. And that string might change so it is not necessary that the string will be always yin_yang sometimes it can be motorbike or anything else.

It Look like JSON String Use the JSONParser in java
JSONObject jobject=new JSONObject(STRING);
String value=jobject.getString("product_tags");
EDITED
Using REGEX
String json="{\"product_tags\":\"yin_yang,yin yang\"}";
json=json.replaceAll("([{}]+)", "");
String value[]=json.split(":");
System.out.print(value[1]);

You can use StringTokenizer to parse your string
String str ="{\"product_tags\":\"yin_yang,yin yang\"}";
StringTokenizer to = new StringTokenizer(str,":}");
while(to.hasMoreTokens()){
String firstString = (String) to.nextElement();
String secondString = (String) to.nextElement();
System.out.print(secondString);
}

Related

Java Reg Expression

I have a question that how can achieve the following using java regexp.
Consider my string say:
a = "activity=play, then I play cricket"
Here my requirement is,
if the above string "activity=play" then I should validate that string contains "cricket" as mentioned above.
if the above string contains "activity=noplay" then nothing should be present at the last of the string. (i.e. The above string should have cricket at the last).
How should I do it?
You do not need a regular expression if you just want to see if a string contains another string. You could do something like so:
String str = "...";
boolean isValid = false;
if(str.contains("activity=play"))
isValid = str.contains("cricket");
else if(str.contains("activity=noplay")
isValid = !str.contains("cricket")
String reg = "activity=play.*cricket";
String str = ".....";
boolean isValide = str.matches(reg);

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

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.

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