How to search a string/word in a hyperlink:Java - java

I need to search a word upload in the URL as "http://res.cloudin.com/sync/image/upload/IMG_8_Jul_2017_10:58:08_pm.jpg".
Later need to replace upload with some other word like w4_c.h_fit in the same link.
Matcher is not able to find upload.
Need help
My code is as below:
String updatedStr;
String keyword1="upload";
String keyword2="IMG";
String regex1 = "\\b"+keyword1+"\\b";
Pattern pattern1 = Pattern.compile(regex1);
Matcher matcher1 = pattern1.matcher(str);
int endUpload = matcher1.end();
String str1 = str.substring(0,endUpload);
String regex2 = "\\b"+keyword2+"\\b";
Pattern pattern2 = Pattern.compile(regex2);
Matcher matcher2 = pattern2.matcher(str);
int startImg = matcher2.start();
String str2 = str.substring(startImg);
updatedStr = str1 + "w_0.5,h_0.5,c_fit" +str2;

Like Stultuske said, use a replace instead when you only have static characters e.g.
String str = "http://res.cloudin.com/sync/image/upload/IMG_8_Jul_2017_10:58:08_pm.jpg";
String keyword1="upload";
String keyword2="IMG";
String updatedStr = str.replace("/"+keyword1+"/", "/"+keyword2+"/");

Related

How can i extract substring from the string using regex in Java?

I have a String xxxxxxxxsrc="/slm/attachment/63338424306/Note.jpg"xxxxxxxx Now, I want to extract substrings slm/attachment/63338424306/Note.jpg & Note.jpg from the String in to variables i.e. temp1 & temp2.
How can I do that using regex in Java?
Note: 63338424306 could be any random no. & Note.jpg could be anything
like Note.png or abc.jpg or xxxx.yyy etc.
Please help me to extract these two strings using regex.
You can use negative look behind to get file name
((?:.(?<!/))+)\"
and below regex to get full path
/(.*)\"
Sample code
public static void main(String[] args) {
Pattern pattern = Pattern.compile("/(.*)\"");
Pattern pattern1 = Pattern.compile("((?:.(?<!/))+)\"");
String matchString = "/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
Matcher matcher = pattern.matcher(matchString);
String fullString = "";
while (matcher.find()) {
fullString = matcher.group(1);
}
matcher = pattern1.matcher(matchString);
String fileName = "";
while (matcher.find()) {
fileName = matcher.group(1);
}
System.out.println(fullString + " " + fileName);
}
As per your comment taking the string as declared below in my code:
Please clarify if your input string is not like this or I'm missing something.
public static void main(String[] args) {
String str = "xxxxxxxxsrc=\"/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
String url = null;
// The below pattern will grab string between quotes
Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
url = m.group(1);
}
// and this will grab filename from the path(url)
p = Pattern.compile("(?:.(?<!/))+$");
m = p.matcher(url);
while (m.find()) {
System.out.println(m.group());
}
}

Java Json String extract number and replace specific text

I have a text file in json, and I want to replace NumberInt(x) with the number x.
In the text file, there are records/data which is in json that has a field workYear: NumberInt(2010) as an example.
I want to replace this into workYear: 2010 by removing NumberInt( and ).
This NumberInt(x) is located anywhere in text file and I want to replace all of it with its number.
I can search all the occurences of this, but I am not sure how to replace it with just the number value.
String json = <json-file-content>
String sPattern = "NumberInt\\([0-9]+\\)";
Pattern pattern = Pattern.compile(sPattern);
Matcher matcher = pattern.matcher(json);
while (matcher.find()) {
String s = matcher.group(0);
int workYear = Integer.parseInt(s.replaceAll("[^0-9]", ""));
System.out.println(workYear);
}
I would like to replace all the NumberInt(x) with just the number value int json String... then I will update the text file (json file).
Thanks!
Following should work. You need to capture the tokens.
String json = "workYear:NumberInt(2010) workYear:NumberInt(2011)";
String sPattern = "NumberInt\\(([0-9]+)\\)";
Pattern pattern = Pattern.compile(sPattern);
Matcher matcher = pattern.matcher(json);
List<String> numbers = new ArrayList<>();
while (matcher.find()) {
String s = matcher.group(1);
numbers.add(s);
}
for (String number: numbers) {
json = json.replaceAll(String.format("NumberInt\\(%s\\)", number), number);
}
System.out.println(json);
You could build the output using a StringBuilder like below,
Please refer to JavaDoc for appendReplacement for info on how this works.
String s = "workYear: NumberInt(2010)\nworkYear: NumberInt(2012)";
String sPattern = "NumberInt\\([0-9]+\\)";
Pattern pattern = Pattern.compile(sPattern);
Matcher matcher = pattern.matcher(s);
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
String s2 = matcher.group(0);
int workYear = Integer.parseInt(s2.replaceAll("[^0-9]", ""));
matcher.appendReplacement(sb, String.valueOf(workYear));
}
matcher.appendTail(sb);
String result = sb.toString();

Match everything after and before something regex Java

Here is my code:
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern p = Pattern.compile("(?<=.com\\/excludethis).*\\/"); //search for this pattern
Matcher m = p.matcher(stringToSearch); //match pattern in StringToSearch
String store= "";
// print match and store match in String Store
if (m.find())
{
String theGroup = m.group(0);
System.out.format("'%s'\n", theGroup);
store = theGroup;
}
//repeat the process
Pattern p1 = Pattern.compile("(.*)[^\\/]");
Matcher m1 = p1.matcher(store);
if (m1.find())
{
String theGroup = m1.group(0);
System.out.format("'%s'\n", theGroup);
}
I want to to match everything that is after excludethis and before a / that comes after.
With "(?<=.com\\/excludethis).*\\/" regex I will match 123456/ and store that in String store. After that with "(.*)[^\\/]" I will exclude / and get 123456.
Can I do this in one line, i.e combine these two regex? I can't figure out how to combine them.
Just like you have used a positive look behind, you can use a positive look ahead and change your regex to this,
(?<=.com/excludethis).*(?=/)
Also, in Java you don't need to escape /
Your modified code,
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern p = Pattern.compile("(?<=.com/excludethis).*(?=/)"); // search for this pattern
Matcher m = p.matcher(stringToSearch); // match pattern in StringToSearch
String store = "";
// print match and store match in String Store
if (m.find()) {
String theGroup = m.group(0);
System.out.format("'%s'\n", theGroup);
store = theGroup;
}
System.out.println("Store: " + store);
Prints,
'123456'
Store: 123456
Like you wanted to capture the value.
This may be useful for you :)
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern pattern = Pattern.compile("excludethis([\\d\\D]+?)/");
Matcher matcher = pattern.matcher(stringToSearch);
if (matcher.find()) {
String result = matcher.group(1);
System.out.println(result);
}
If you don't want to use regex, you could just try with String::substring*
String stringToSearch = "https://example.com/excludethis123456/moretext";
String exclusion = "excludethis";
System.out.println(stringToSearch.substring(stringToSearch.indexOf(exclusion)).substring(exclusion.length(), stringToSearch.substring(stringToSearch.indexOf(exclusion)).indexOf("/")));
Output:
123456
* Definitely don't actually use this

How can i replace this?

How can I replace this
String str = "KMMH12DE1433";
String pattern = "^[a-z]{2}([0-9]{2})[a-z]{1,2}([0-9]{4})$";
String str2 = str.replaceAll(pattern, "repl");
Log.e("Founded_words2",str2);
What I got: KMMH12DE1433
What I want: MH12DE1433
Try it like this using a proper java.util.regex.Pattern and a java.util.regex.Matcher:
String str = "KMMH12DE1433";
//Make the pattern, case-insensitive using (?i)
Pattern pattern = Pattern.compile("(?i)[a-z]{2}([0-9]{2})[a-z]{1,2}([0-9]{4})");
//Create the Matcher
Matcher m = pattern.matcher(str);
//Check if we find anything
if(m.find()) {
//Use what you found - with proper capturing groups you
//gain access to parts of your pattern as needed
System.out.println("Found this: " + m.group());
}
If you just want to remove the first two characters and if the first two characters will always be uppercase letters:
String str = "KMMH12DE1433";
String pattern = "^[A-Z]{2}";
String str2 = str.replaceAll(pattern, "");
Log.e("Output string: ", str2);
try this :
String a = "KMMH12DE1433";
String pattern = "^[A-Z]{2}";
String rs = a.replaceAll(pattern,"");
Please change like this
String ans=str.substring(0);

regex extract string between two characters

I would like to extract the strings between the following characters in the given string using regex in Java:
/*
1) Between \" and \" ===> 12222222222
2) Between :+ and # ===> 12222222222
3) Between # and > ===> 192.168.140.1
*/
String remoteUriStr = "\"+12222222222\" <sip:+12222222222#192.168.140.1>";
String regex1 = "\"(.+?)\"";
String regex2 = ":+(.+?)#";
String regex3 = "#(.+?)>";
Pattern p = Pattern.compile(regex1);
Matcher matcher = p.matcher(remoteUri);
if (matcher.matches()) {
title = matcher.group(1);
}
I am using the above given code snippet, its not able to extract the strings that I want it to. Am I doing anything wrong? Meanwhile, I am quite new to regex.
The matches() method attempts to match the regular expression against the entire string. If you want to match a part of the string, you want the find() method:
if (matcher.find())
You could, however, build a single regular expression to match all three parts at once:
String regex = "\"(.+?)\" \\<sip:\\+(.+?)#(.+?)\\>";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(remoteUriStr);
if (matcher.matches()) {
title = matcher.group(1);
part2 = matcher.group(2);
ip = matcher.group(3);
}
Demo: http://ideone.com/8t2EC
If your input always looks like that and you always want the same parts from it you can put that in a single regex (with multiple capturing groups):
"([^"]+)" <sip:([^#]+)#([^>]+)>
So you can then use
Pattern p = Pattern.compile("\"([^\"]+)\" <sip:([^#]+)#([^>]+)>");
Matcher m = p.matcher(remoteUri);
if (m.find()) {
String s1 = m.group(1);
String s2 = m.group(2);
String s3 = m.group(3);
}

Categories