Java replaceall ignore case and special characters - java

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.

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

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

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

Java RegEx replace all characters in string except for a word

I am using the code in Java:
String word = "hithere";
String str = "123hithere12345hi";
output(str.replaceAll("(?!"+word+")", "x"));
However, rather than outputting: xxxhitherexxxxxxx like I want it to, it outputs: x1x2x3hxixtxhxexrxex1x2x3x4x5xhxix x, I've tried a load of different regex patterns to try to do this, but I can't seem to figure out how to do this :(
Any help would be much appreciated.
Well this technically works. Using only replace all and only one line, and it's assuming you string does not contain a deprecated ASCII character (BEL)
String string = "hithere";
String string2 = "asdfasdfasdfasdfhithereasasdf";
System.out.println(string2.replaceAll(string,"" + (char)string.length()).replaceAll("[^" + (char)string.length() + "]", "x").replaceAll("" + (char)string.length(), string));
I think this is what you're looking for, if I'm not mistaken:
String pattern = "(\\d)|(hi$)";
System.out.println("123hithere12345hi".replaceAll(pattern, "X"));
The pattern replaces any numeric digits and the word "hi".
This lookaround based code will work for you:
String word = "hithere";
String string = "123hithere12345hi";
System.out.println(string.replaceAll(
".(?=.*?\\Q" + word + "\\E)|(?<=\\Q" + word + "\\E(.){0,99}).", "x"));
//=> xxxhitherexxxxxxx

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

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