I have a String which has numbers and I want to add this sign ":" between every two numbers as if the string was 0123456789 I want it to be like this 01:23:45:67:89
Is there any way to insert it ?? as I read about replace() but this does not help in my case
You could use this magic piece of regex:
System.out.println("0123456789".replaceAll(".{2}(?!$)", "$0:"));
.{2} match 2 characters
(?!$) not at end
$0: First matched argument with : included
String x="0123456789";
String result="";
for(int i=0;i<x.length();i++){
result+=x.charAt(i);
if(i%2==1 && i+1<x.length())
result+=":";
}
Related
I have a string that it can contains commas, but not only commas.
For example:
"," is wrong
"hello, my dear" is right
",,,," is wrong
",,hello" is right
For this reason I don't think I can use regex. How could I test this situation avoiding simple comparison like this one?
myString.equals(",") || myString.equals(",,") || ....
The easiest solution, IMHO, would be to stream the characters, and check that they are all ',':
boolean onlyCommas = myString.chars().allMatch(c -> c == ',');
A regex is actually what you're looking for:
boolean result = myString.matches("^,+$");
^ represents the beginning of the string, $ represents the end of the string and ,+ matches only (and at least one) comma characters. This way you match any string that only consists of comma characters.
String replacedString = someString.replace(",", "");
If it was made up of just commas the string will be empty afterwards.
As i haven't much worked on regex, can someone help me out in getting the answer for below thing:
(1)I want to remove a text say Element
(2)It may of may not followed by delimiter say pipe(||)
I tried below thing, but it is not working in the way i want:
String str = "String:abc||Element:abc||Value:abc"; // Sample text 1
String str1 = "String:abc||Element:abc"; // Sample text 2
System.out.println(str.replaceFirst("Element.*\\||", ""));
System.out.println(str1.replaceFirst("Element.*\\||", ""));
Required output in above cases:
String:abc||Value:abc //for the first case
String:abc //for the second case
Assuming that you can decide to give another value to the original pattern which is Element in this case, you can use Pattern.quote to escape it as below:
String str = "String:abc||Element:abc||Value:abc"; // Sample text 1
String str1 = "String:abc||Element:abc"; // Sample text 2
String originalPattern = "Element";
String pattern = String.format("\\|{2}%s[^\\|]+", Pattern.quote(originalPattern));
System.out.println(str.replaceFirst(pattern, ""));
System.out.println(str1.replaceFirst(pattern, ""));
Your patter is then generic and its value is String.format("\\|{2}%s[^\\|]+", Pattern.quote(originalPattern))
Output:
String:abc||Value:abc
String:abc
You put the escape wrong. It should be:
Element(.*?\|\||.*$)
Put the escape on each pipe, and use ? for non greedy Regex so you only replace just enough string, not everything.
String text = "String:abc||Element:abc||Value:abc";
text = text.replaceAll("\\belement\\b", "");
you might need to use replace all this will replace all element from your string here i am using '\b' word boundary in java regular expression in between the words
I have a string which is of the form
String str = "124333 is the otp of candidate number 9912111242.
Please refer txn id 12323335465645 while referring blah blah.";
I need 124333, 9912111242 and 12323335465645 in a string array. I have tried this with
while (Character.isDigit(sms.charAt(i)))
I feel that running the above said method on every character is inefficient. Is there a way I can get a string array of all the numbers?
Use a regex (see Pattern and matcher):
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(<your string here>);
while (m.find()) {
//m.group() contains the digits you want
}
you can easily build ArrayList that contains each matched group you find.
Or, as other suggested, you can split on non-digits characters (\D):
"blabla 123 blabla 345".split("\\D+")
Note that \ has to be escaped in Java, hence the need of \\.
You can use String.split():
String[] nbs = str.split("[^0-9]+");
This will split the String on any group of non-numbers digits.
And this works perfectly for your input.
String str = "124333 is the otp of candidate number 9912111242. Please refer txn id 12323335465645 while referring blah blah.";
System.out.println(Arrays.toString(str.split("\\D+")));
Output:
[124333, 9912111242, 12323335465645]
\\D+ Matches one or more non-digit characters. Splitting the input according to one or more non-digit characters will give you the desired output.
Java 8 style:
long[] numbers = Pattern.compile("\\D+")
.splitAsStream(str)
.mapToLong(Long::parseLong)
.toArray();
Ah if you only need a String array, then you can just use String.split as the other answers suggests.
Alternatively, you can try this:
String str = "124333 is the otp of candidate number 9912111242. Please refer txn id 12323335465645 while referring blah blah.";
str = str.replaceAll("\\D+", ",");
System.out.println(Arrays.asList(str.split(",")));
\\D+ matches one or more non digits
Output
[124333, 9912111242, 12323335465645]
First thing comes into my mind is filter and split, then i realized that it can be done via
String[] result =str.split("\\D+");
\D matches any non-digit character, + says that one or more of these are needed, and leading \ escapes the other \ since \D would be parsed as 'escape character D' which is invalid
In Java, how can I take a string as a parameter, and then remove all punctuation and spaces and then convert the rest of the letters to uppercase?
Example 1:
Input: How's your day going?
Output: HOWSYOURDAYGOING
Example 2:
Input: What's your name again?
Output: WHATSYOURNAMEAGAIN
This should do the trick
String mystr= "How's your day going?";
mystr = mystr.replaceAll("[^A-Za-z]+", "").toUpperCase();
System.out.println(mystr);
Output:
HOWSYOURDAYGOING
The regex [^A-Za-z]+ means one or more characters that do not match anything in the range A-Za-z, and we replace them with the empty string.
String yourString = "How's your day going";
yourString=yourString.replaceAll("\\s+",""); //remove white space
yourString=yourString.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
yourString=yourString.toUpperCase(); //convert to Upper case
I did it with
inputText = inputText.replaceAll("\\s|[^a-zA-Z0-9]","");
inputText.toUpper(); //and later uppercase the complete string
Though #italhourne 's answer is correct but you can just reduce it in single step by just removing the spaces as well as keeping all the characters from a-zA-Z and 0-9, in a single statement by adding "or".
Just a help for those who need it!!
public static String repl1(String n){
n = n.replaceAll("\\p{Punct}|\\s","");
return n;
}
Well, I did it the long way, take a look if you want. I used the ACII code values (this is my main method, transform it to a function on your own).
String str="How's your day going?";
char c=0;
for(int i=0;i<str.length();i++){
c=str.charAt(i);
if(c<65||(c>90&&c<97)||(c>122)){
str=str.replace(str.substring(i,i+1) , "");
}
}
str=str.toUpperCase();
System.out.println(str);
I have a simple method splitting a string into an array. It splits it where there are non-letter characters. The line I am using right now is as follows:
String[] words = str.split("[^a-zA-Z]");
So this should split the string where there are only alphabetical characters. But the problem is that when it splits it works for some, but not all. For example:
String str = "!!day--yaz!!";
String[] words = str.split("[^a-zA-Z]");
String result = "";
for (int i = 0; i < words.length; i++) {
result += words[i] + "1 ";
}
return result;
I added the 1 in there to see where the split takes place, becuase i was getting errors on null values. Anyway, when I run this code I get an output of:
1 1 day1 1 yaz1
Why is it splitting between the first two !'s and after one of the -'s, but not after the last two !'s? Why is it even splitting there at all? Any help on this would be great!
It doesn't split before or after it splits ON the matches, therefore you get an empty String between the dashes and the bangs.
This doesn't apply to the trailing bangs, because trailing empty Strings are omitted as described in the javadoc
Trailing empty strings are therefore not included in the resulting
array.
This happens because it indeed uses every non-letter character as a delimiter. It means that string "!" will be splitted into array of 2 empty strings to the left and to the right of the exclamation sign.
Your problem can be solved withing 2 steps.
use "[^a-zA-Z]+" instead of "[^a-zA-Z]". The + will help you to avoid empty string between 2 dashes.
Remove starting and trailing non-letter characters before splitting. This will remove leading and trailing empty strings: str.replaceFirst("[^a-zA-Z]+").replaceFirst("[^a-zA-Z]+$")
Finally your split will look like:
String[] words = str..replaceFirst("[^a-zA-Z]+").replaceFirst("[^a-zA-Z]+$")split("[^a-zA-Z]");
If you want to get rid of some of the extra splits, use split("[^a-zA-Z]+") instead of split("[^a-zA-Z]"). This will match a continuous part of the String that matches the pattern.