In Java I have a String
String string = "sdfgjhjdfg.m\"gb=1234509876\"xcvbnfghj".
I want to replace it with Hi="1234509876".
In string replace function i could not do this.
string = string.replace(".*gb=(.*)\".*","Hi=(.*)");
In the 2nd parameter (.*) group, the group in 1st parameters should get replace
Please Help me....
Try to use the following code for getting number string from main string
public static void main(String[] args)
{
String string = "sdfgjhjdfg.m\"gb=1234509876\"xcvbnfghj";
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(string);
while (m.find()) {
string=m.group();
}
System.out.println("res"+string);
}
You can try something like this
String string = "sdfgjhjdfg.m\"gb=1234509876\"xcvbnfghj";
String newStr=string.replaceAll("gb=1234509876","Hi=1234509876");
System.out.println(newStr);
try
string = string.replace("gb=","Hi=");
try this
String string = "sdfgjhjdfg.m\"gb=1234509876\"xcvbnfghj";
System.out.println(string);
string = string.replaceAll("gb=-?\\d+","Hi='new value'");
System.out.println(string);
Related
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());
}
}
String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i++;", "");
// Desired output :: newCode = "helloworld";
But this is not replacing i++ with blank.
just use replace() instead of replaceAll()
String preCode = "helloi++;world";
String newCode = preCode.replace("i++;", "");
or if you want replaceAll(), apply following regex
String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i\\+\\+;", "");
Note : in the case of replace() the first argument is a character sequence, but in the case of replaceAll the first argument is regex
try this one
public class Practice {
public static void main(String...args) {
String preCode = "Helloi++;world";
String newCode = preCode.replace(String.valueOf("i++;"),"");
System.out.println(newCode);
}
}
The problem is the string that you are using to replace , that is cnsidered as regex pattern to skip the meaning you will have to use escape sequence like below.
String newCode = preCode.replaceAll("i\\+\\+;", "");
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+"/");
I'm just trying to remove (replace with "") \r and \n from my JSON. Here is the method I'm currently testing which doesn't work.
public static void testing(){
String string = "\r\r\r\n\n\n";
string.replace("\r", "");
string.replace("\n", "");
}
Try this regex (\\r\\n|\\n|\\r) and String#replaceAll, like:
string = string.replaceAll("(\\r\\n|\\n|\\r)", "");
After replacing you need to assign back to the original string. Because the string is immutable you cannot change the value of a string.
You need to use
String string = "\r\r\r\n\n\n";
string = string.replace("\r", "");
string = string.replace("\n", "");
Or you can use any libraries like Apache StringUtils.If you are using these utils , no needs to assign back the value to String
try this:
public static void testing(){
String string = "\r\r\r\n\n\n";
string = string.replace("\r", "");
string = string.replace("\n", "");
}
because replace return another string(new String) because String is immutable so unable to modified directly
String.replace will return a string. It doesn't change its value.
public static void testing(){
String str = "\r\r\r\n\n\n";
str = str.replace("\r", "");
str = str.replace("\n", "");
}
String string = "\r\r\r\n\n\n";
String newStr = string.replace("\r", "");
newStr = newStr.replace("\n", "");
System.out.println(newStr);
String will return new String Object.
try this:
String string = "\rte\r\rs\nti\nn\ng";
String newString = string.replaceAll("[^\\w]", "");
String string = "\r\r\r\n\n\n";
string = string.replaceAll("\r", "");
string = string.replaceAll("\n", "");
Try this,
string = string.replaceAll("[\r\n]", "");
Here is what I found:
data_json = data_json.replaceAll("\\\\r\\\\n", "");
Copied from OP's comment.
I want to know how can copy the "?ned=us&topic=t" part in "http://news.google.com/?ned=us&topic=t". Basically, I want to copy the path of the url, or the portion after the ".com". How do I do this?
public class Example {
public static String url = "http://news.google.com/?ned=us&topic=t";
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get(url);
WebElement reportCln=driver.findElement(By.id("id_submit_button"));
String path=driver.getCurrentUrl();
System.out.println(path);
}
}
You should have a look at the java.net.URL class and its getPath() and getQuery() methods.
#Test
public void urls() throws MalformedURLException {
final URL url = new URL("http://news.google.com/?ned=us&topic=t");
assertEquals("ned=us&topic=t", url.getQuery());
assertEquals("?ned=us&topic=t", "?" + url.getQuery());
assertEquals("/", url.getPath());
}
Regular expressions are fun, but IMO this is easier to understand.
Try this:
String request_uri = null;
String url = "http://news.google.com/?ned=us&topic=t";
if (url.startsWith("http://") {
request_uri = url.substring(7).split("/")[1];
} else {
request_uri = url.split("/")[1];
}
System.out.println (request_uri); // prints: ?ned=us&topic=t
If you're only interested in the query string i.e. for google.com/search?q=key+words you want to ignore search? then just split on ? directly
// prints: q=key+words
System.out.println ("google.com/search?q=key+words".split("\\?")[0]);
You can use regular expression to extract the part you want:
String txt = "http://news.google.com/?ned=us&topic=t";
String re1 = "(http:\\/\\/news\\.google\\.com\\/)"; // unwanted part
String re2 = "(\\?.*)"; // wanted part
Pattern p = Pattern.compile(re1 + re2, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(txt);
if (m.find())
{
String query = m.group(2);
System.out.print(query);
}