remove : in 12:45 (java) - java

time 12:45
i want to remove : in java .. i just need 1245 ..How can i do that?

String time = "12:45".replace( ":", "" ); // "1245"
If you have Apache Coomons Lang in your classpath, and you are not sure that time is not null, you could use StringUtils:
time = StringUtils.remove( time, ":" );
this way is more compact than writing
if ( time != null ) {
time = time.replace( ":", "" );
}

There is the "replace" method.
s = s.replace(':','');
If you want to get fancy:
s = s.replaceAll("[^a-zA-Z0-9]", "");
This will remove all non-alpha numeric characters (including your ':')
All right there in the JavaDoc.

If "12:45" is a string, then just use "12:45".replaceAll(":", "").

String strTime = "12:45";
strTime.replace(':','');

For the easiest method, use replace:
String time = "12:45";
time = time.replace(':', "");
but you can use regular expressions:
Pattern pattern = new Pattern("(\\d{1,2}):(\\d{1,2})");
Matcher matcher = pattern.matcher("12:45");
String noColon = matcher.group(1) + matcher.group(2);
or the String API:
String time = "12:45";
int colonIndex = time.indexOf(':"';
String noColon = time.substring(0, colonIndex) +
time.substring(colonIndex + 1, time.length);

Like what others told, a method as simple as String's replace should suffice, but since i suspect your input is a date, have a look at SimpleDateFormat too.

Related

Check if an intermediate string starts-ends with certain pattern and update the string

If I have a string like :
String str = "startDate:23/04/2016;endDate:;renewDate;"
Required multiple operation on the string.I need to get a String and extract different sub-strings using a delimiter (";") then again extract different sub-strings to form a key-value using a delimiter (":"). If against the key their is no value present the update with diff-diff default value like ("01/01/2000","01/01/1900" since both are of type Date).
if you notice for renewDate field their is no separator (":") in this case we need to append the separator along with default value (:01/01/1900) so that my expected result would be like :
String str = "startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;"
I have tried below regex but it is not working for all scenario :
String regExpression = "(?<=\\bendDate:)[;]+"
str = str.replaceAll(regExpression , "01/01/2000");
Can any one guide me how to achive the result using regex.Thanks!!!!!
As Tim said we can use regex pattern to replace the value. Adding to his answer, the only change I recommend to add colon(:) as optional in pattern used for both renewDate and endDate in text.
String endDate = "01/01/2000";
String renewDate = "01/01/1900";
String str = "startDate:23/04/2016;endDate:;renewDate;";
str = str.replaceAll(";endDate:?;", ";endDate:"+endDate+";");
str = str.replaceAll(";renewDate:?;", ";renewDate:"+renewDate+";");
System.out.println(str);
This will give the output as below
startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;
Using a regex replacement, we can try:
String endDate = "01/01/2000";
String renewDate = "01/01/1900";
String str = "startDate:23/04/2016;endDate:;renewDate:;";
String output = str.replaceAll("\\bendDate:;", "endDate:" + endDate + ";")
.replaceAll("\\brenewDate:;", "renewDate:" + renewDate + ";");
System.out.println(output);
This prints:
startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;
The logic here is to only target empty end and renew date fields, including default values if needed.
Alternatively, separate strings based on your first delimiter ; and then :.
String str = "startDate:23/04/2016;endDate:;renewDate;";
String dates[] = str.split(";");
for(String date : dates){
String default[] = date.split(":");
output.append(default[0] + ":" + (default.length > 1 ? default[1] : defaultDate));
}

regex to match and replace two characters between string

I have a string String a = "(3e4+2e2)sin(30)"; and i want to show it as a = "(3e4+2e2)*sin(30)";
I am not able to write a regular expression for this.
Try this replaceAll:
a = a.replaceAll("\) *(\\w+)", ")*$1");
You can go with this
String func = "sin";// or any function you want like cos.
String a = "(3e4+2e2)sin(30)";
a = a.replaceAll("[)]" + func, ")*siz");
System.out.println(a);
this should work
a = a.replaceAll("\\)(\\s)*([^*+/-])", ") * $2");
String input = "(3e4+2e2)sin(30)".replaceAll("(\\(.+?\\))(.+)", "$1*$2"); //(3e4+2e2)*sin(30)
Assuming the characters within the first parenthesis will always be in similar pattern, you can split this string into two at the position where you would like to insert the character and then form the final string by appending the first half of the string, new character and second half of the string.
string a = "(3e4+2e2)sin(30)";
string[] splitArray1 = Regex.Split(a, #"^\(\w+[+]\w+\)");
string[] splitArray2 = Regex.Split(a, #"\w+\([0-9]+\)$");
string updatedInput = splitArray2[0] + "*" + splitArray1[1];
Console.WriteLine("Input = {0} Output = {1}", a, updatedInput);
I did not try but the following should work
String a = "(3e4+2e2)sin(30)";
a = a.replaceAll("[)](\\w+)", ")*$1");
System.out.println(a);

Replace String in Java with regex and replaceAll

Is there a simple solution to parse a String by using regex in Java?
I have to adapt a HTML page. Therefore I have to parse several strings, e.g.:
href="/browse/PJBUGS-911"
=>
href="PJBUGS-911.html"
The pattern of the strings is only different corresponding to the ID (e.g. 911). My first idea looks like this:
String input = "";
String output = input.replaceAll("href=\"/browse/PJBUGS\\-[0-9]*\"", "href=\"PJBUGS-???.html\"");
I want to replace everything except the ID. How can I do this?
Would be nice if someone can help me :)
You can capture substrings that were matched by your pattern, using parentheses. And then you can use the captured things in the replacement with $n where n is the number of the set of parentheses (counting opening parentheses from left to right). For your example:
String output = input.replaceAll("href=\"/browse/PJBUGS-([0-9]*)\"", "href=\"PJBUGS-$1.html\"");
Or if you want:
String output = input.replaceAll("href=\"/browse/(PJBUGS-[0-9]*)\"", "href=\"$1.html\"");
This does not use regexp. But maybe it still solves your problem.
output = "href=\"" + input.substring(input.lastIndexOf("/")) + ".html\"";
This is how I would do it:
public static void main(String[] args)
{
String text = "href=\"/browse/PJBUGS-911\" blahblah href=\"/browse/PJBUGS-111\" " +
"blahblah href=\"/browse/PJBUGS-34234\"";
Pattern ptrn = Pattern.compile("href=\"/browse/(PJBUGS-[0-9]+?)\"");
Matcher mtchr = ptrn.matcher(text);
while(mtchr.find())
{
String match = mtchr.group(0);
String insMatch = mtchr.group(1);
String repl = match.replaceFirst(match, "href=\"" + insMatch + ".html\"");
System.out.println("orig = <" + match + "> repl = <" + repl + ">");
}
}
This just shows the regex and replacements, not the final formatted text, which you can get by using Matcher.replaceAll:
String allRepl = mtchr.replaceAll("href=\"$1.html\"");
If just interested in replacing all, you don't need the loop -- I used it just for debugging/showing how regex does business.

how to extract this using regex

I need to extract this
Example:
www.google.com
maps.google.com
maps.maps.google.com
I need to extraact google.com from this.
How can I do this in Java?
Split on . and pick the last two bits.
String s = "maps.google.com";
String[] arr = s.split("\\.");
//should check the size of arr here
System.out.println(arr[arr.length-2] + '.' + arr[arr.length-1]);
Assuming you want to get the top level domain out of the hostname, you could try this:
Pattern pat = Pattern.compile( ".*\\.([^.]+\\.[^.]+)" ) ;
Matcher mat = pat.matcher( "maps.google.com" ) ;
if( mat.find() ) {
System.out.println( mat.group( 1 ) ) ;
}
if it's the other way round, and you want everything excluding the last 2 parts of the domain (in your example; www, maps, and maps.maps), then just change the first line to:
Pattern pat = Pattern.compile( "(.*)\\.[^.]+\\.[^.]+" ) ;
Extracting a known substring from a string doesn't make much sense ;) Why would you do a
String result = address.replaceAll("^.*google.com$", "$1");
when this is equal:
String result = "google.com";
If you need a test, try:
String isGoogle = address.endsWith(".google.com");
If you need the other part from a google address, this may help:
String googleSubDomain = address.replaceAll(".google.com", "");
(hint - the first line of code is a solution for your problem!)
String str="www.google.com";
try{
System.out.println(str.substring(str.lastIndexOf(".", str.lastIndexOf(".") - 1) + 1));
}catch(ArrayIndexOutOfBoundsException ex){
//handle it
}
Demo

How to remove " " from java string

I have a java string with " " from a text file the program accesses with a Buffered Reader object. I have tried string.replaceAll(" ","") and it doesn't seem to work.
Any ideas?
cleaned = cleaned.replace(" "," ");
cleaned = cleaned.replace("\u00a0","")
This is a two step process:
strLineApp = strLineApp.replaceAll("&"+"nbsp;", " ");
strLineApp = strLineApp.replaceAll(String.valueOf((char) 160), " ");
This worked for me. Hope it helps you too!
The same way you mentioned:
String cleaned = s.replace(" "," ");
It works for me.
There's a ready solution to unescape HTML from Apache commons:
StringEscapeUtils.unescapeHtml("")
You can also escape HTML if you want:
StringEscapeUtils.escapeHtml("")
Strings are immutable so You need to do
string = string.replaceAll(" ","")
You can use JSoup library:
String date = doc.body().getElementsByClass("Datum").html().toString().replaceAll(" ","").trim();
String.replace(char, char) takes char inputs (or CharSequence inputs)
String.replaceAll(String, String) takes String inputs and matches by regular expression.
For example:
String origStr = "bat";
String newStr = str.replace('a', 'i');
// Now:
// origStr = "bat"
// newStr = "bit"
The key point is that the return value contains the new edited String. The original String variable that invokes replace()/replaceAll() doesn't have its contents changed.
For example:
String origStr = "how are you?";
String newStr = origStr.replaceAll(" "," ");
String anotherStr = origStr.replaceAll(" ","");
// origStr = "how are you?"
// newStr = "how are you?"
// anotherStr = howareyou?"
We can have a regular expression check and replace HTML nbsp;
input.replaceAll("[\\s\\u00A0]+$", "") + "");
It removes non breaking spaces in the input string.
My solution is the following, and only this worked for me:
String string = stringWithNbsp.replaceAll("NNBSP", "");
Strings in Java are immutable. You have to do:
String newStr = cleaned.replaceAll(" ", "");
I encountered the same problem: The inner HTML of the element I needed had "&nbsp" and my assertion failed.
Since the question has not accepted any answer,yet I would suggest the following, which worked for me
String string = stringwithNbsp.replaceAll("\n", "");
P.S : Happy testing :)

Categories