If I am given a integer value like 100, then I have to update all the occurrences of the text "Writing No 1" to "Writing No 101"
Actual text:
Collection reference 4 -> My Main Text 4 -> It's writing 3 Writing No 1
Writing No 2 Writing NO 3
I have given three previous references.
As I am given the 100, so I output would like this.
Collection reference 4 -> My Main Text 104 -> It's writing 3 Writing No 101
Writing No 102 Writing NO 103
I have given three previous references.
How to update Writing No 1 to Writing NO 101 and other in the same way using Java?
As per my understanding from your question, you got to replace the string based on the integer values.
Better you write a function for the same like this-
String text = new String("Writing No 1");
public void demo(int num) {
text .replace(text.slice(-1), num);
}
Where you can pass any integer value and can even use loop for the multiple string values.
Hope i was helpful.
Not 100% this is what you need, but I'll give it a try:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StackOverflow {
public static void main(String[] args) {
int inc = 100;
String text = "Collection reference 4 -> My Main Text 4 -> It's writing 3 Writing No 1 \nWriting No 2 Writing NO 3 \nI have given three previous references.";
String patten = "(\\D+) (\\d) (\\D+) (\\d) (\\D+) (\\d) (\\D+) (\\d) (\\D+) (\\d) (\\D+) (\\d) (\\D+)";
Pattern pattern = Pattern.compile(patten, Pattern.DOTALL);
Matcher matcher = pattern.matcher(text);
matcher.find();
System.out.println(matcher.group(1) + " " + matcher.group(2) + " " + matcher.group(3) + " "
+ inc(matcher.group(4), inc) + " " + matcher.group(5) + " " + matcher.group(6) + " " + matcher.group(7)
+ " " + inc(matcher.group(8), inc) + " " + matcher.group(9) + " " + inc(matcher.group(10), inc) + " "
+ matcher.group(11) + " " + inc(matcher.group(12), inc) + matcher.group(13));
}
private static int inc(String base, int inc) {
return Integer.valueOf(base) + inc;
}
}
Related
I have a string of format :
"A hr B min to C hr D min"
where A, B, C, D will be integers. I want to extract A, B, C, D from this string. A, B, C, D can be single or multi digit integers and I am not really concerned with validation right now (such as C, D would be between 0 and 59 ideally) as that can be taken care of later.
What is the best way to achieve this in Java?
Assuming this text could appear inside a larger text, and that your target phrase might be repeated more than once, we can try matching on the following pattern:
\b(\d+) hr (\d+) min to (\d+) hr (\d+) min\b
Here is a sample Java code:
String input = "blah blah 1 hr 5 min to 2 hr 10 min blah blah";
String regex = "\\b(\\d+) hr (\\d+) min to (\\d+) hr (\\d+) min\\b";
Pattern r = Pattern.compile(regex);
Matcher m = r.matcher(input);
while (m.find()) {
System.out.println("Found values: (" + m.group(1) + ", " + m.group(2) + ", " +
m.group(3) + ", " + m.group(4) + ")");
}
This prints:
Found values: (1, 5, 2, 10)
public class splitString {
public static void main(String[] args) {
String hours = "5 hr 6 min to 17 hr 09 min";
String[] splithours = hours.split(" ");
for(String splitted: splithours) {
if(splitted.matches("[0-9]{2}") || splitted.matches("[0-9]") ) {
System.out.println(splitted);
}
}
}
}
I want to get all string inside the very first parentheses
For example, if the input :
"1 + 2 + ( 1 + 2 + (1 + 2) ) "
It will return
[( 1 + 2 + (1 + 2) )]
If the input :
"1 + (1 + 2 + (1 + 2 + (1 + 2) ) )"
It will return
["(1 + 2 + (1 + 2 + (1 + 2) ) )"]
You can use Pattern & Matcher classes to extract what you want as follows
String input = "1 + (1 + 2 + (1 + 2 + (1 + 2) ) )";
String regexp = "(\\()(.*)(\\))";
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
System.out.println(matcher.group(2));
}
Output
1 + 2 + (1 + 2 + (1 + 2) )
Ensure Password meets the following Criteria
Length: 8-32 characters
Password must contain atleast 3 of the following: Uppercase, Lowercase, Number, Symbol
Password must not contain Spaces
Password Characters allowed:
!##$%^*()_+Aa1~`-={}[]|\:;"',.?/
I tried:
^.*(?=.*[a-z])(?=.*[A-Z])(?=.*[\d\W])^(?!.*[&])(?=.*[!##$%^*()_+Aa1~`\-={}[\]|\:;"',.?/])\S{8,32}$
I have written this Regex, But enforces One uppercase letter which Should not be the case.......It should accept any three combinations of Uppercase, Lowercase, Numbers, Symbols:
!##$%^*()_+Aa1~`-={}[]|\:;"',.?/
The regex limit limit 255 characters. Any suggestions help on this please.
^(?:[A-Z]()|[a-z]()|[0-9]()|[!##$%^*()_+~`={}\[\]|\:;"',.?/-]())+$(?:\1\2\3|\1\2\4|\1\3\4|\2\3\4)
In more readable form:
^
(?:
[A-Z] () |
[a-z] () |
[0-9] () |
[!##$%^*()_+~`={}\[\]|\\:;"',.?/-] ()
)+
$
(?:
\1\2\3 |
\1\2\4 |
\1\3\4 |
\2\3\4
)
What I'm doing is using empty capturing groups as check boxes, tallying which kinds of characters were seen over the course of the match. So, for example, if there's no uppercase letter in the string, group #1 never participates in the match, so \1 won't succeed at the end. Unless all three other groups do participate, the match will fail.
Be aware that this technique doesn't work in all flavors. In JavaScript, for example, a backreference to an empty group always succeeds, even if the group didn't participate in the match.
You can use:
^(?=.*[!##$%^*()_+~`={}|:;"',.?\[\]\/-].*)(?=.*[A-Z].*)(?=.*[a-z].*)[\w!##$%^*()_+~`={}|:;"',.?\[\]\/-]{8,32}$|
^(?=.*[!##$%^*()_+~`={}|:;"',.?\[\]\/-].*)(?=.*\d.*)(?=.*[a-z].*)[\w!##$%^*()_+~`={}|:;"',.?\[\]\/-]{8,32}$|
^(?=.*[!##$%^*()_+~`={}|:;"',.?\[\]\/-].*)(?=.*[A-Z].*)(?=.*\d.*)[\w!##$%^*()_+~`={}|:;"',.?\[\]\/-]{8,32}$|
^(?=.*\d.*)(?=.*[A-Z].*)(?=.*[a-z].*)[\w!##$%^*()_+~`={}|:;"',.?\[\]\/-]{8,32}$
See LiveDemo
If you want a bit more of flexibility you can use this:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Dummy{
public static void main(String []args){
String password = "aaaZZZ111";
String specials = "!##$%^*()_+~`={}|:;\"',.?\\[\\]\\/-";
String uppercase = "A-Z";
String lowercase = "a-z";
String numbers = "\\d";
String all = specials + uppercase + lowercase + numbers;
int min = 8;
int max = 32;
String regex =
"^" + lookahead(specials) + lookahead(uppercase) + lookahead(lowercase) + "[" + all + "]{"+ min +"," + max + "}$|" +
"^" + lookahead(specials) + lookahead(uppercase) + lookahead(numbers) + "[" + all + "]{"+ min +"," + max + "}$|" +
"^" + lookahead(specials) + lookahead(lowercase) + lookahead(numbers) + "[" + all + "]{"+ min +"," + max + "}$|" +
"^" + lookahead(uppercase) + lookahead(lowercase) + lookahead(numbers) + "[" + all + "]{"+ min +"," + max + "}$";
Pattern r = Pattern.compile(regex);
Matcher m = r.matcher(password);
if (m.find()) {
System.out.println("OK");
} else {
System.out.println("NO MATCH");
}
}
public static String lookahead(String input) {
return "(?=.*[" + input + "].*)";
}
}
Generate by use of the operator + a string, that the values in the variable in the given ones on top
Order includes, in each case apart by ",". give the string with System out println (...).
Remove the quotes " and call toString()
str = hexValue.toString() + ", " + octValue.toString() + ", " + l.toString() + ", " + var1.toString() + ", " + var2.toString() + ", " + var3.toString() + ", " + var4.toString() + ", " + c.toString();
now notice that this will give you the decimal values.. if you want the hex, octal, etc, that's a different question.
Suppose we have the following variables:
int age = 5;
String name = "Mohammad";
double weight = 68.4;
If we want to print them out joined in a string with one statement we can say:
System.out.println("My name is " + name + ", I am " + age + " years old, " + " I once caught a fish that weighs " + weight +"kg");
In Java, using the + operator you can concatenate strings.
Note: age, name, and weight are all of different types, but when you put the + operator with a String, java automatically convert that variable to a string and then concatenates it with the rest of the string. Hence, if you wish to perform some kind of operation then concatenate, then you should make use of parentheses ():
System.out.println("Two Plus Five is = " + (2 + 5));
Just starting learning java today and can't seem to figure this out. I am following the tutorial on learnjavaonline.org which teaches you a few things and then asks you to write a code to do a specific thing, it then checks the output to see if its correct. The thing is, if its not correct, it doesn't say why, or give you an example of the correct code.
It wants me to output a string saying "H3110 w0r1d 2.0 true" using all of the primitives
i came up with this
public class Main {
public static void main(String[] args) {
char h = 'H';
byte three = 3;
short one = 1;
boolean t = true;
double ten = 10;
float two = (float) 2.0;
long won = 1;
int zero = 0;
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
System.out.println(output);
}
}
but it outputs 86.0 w0r1d 2.0 true
how can i make it so it doesn't add all the integers, but displays them consecutively?
The problem with this line:
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
is that operations are performed left to right, so it first sums h + three (which evaluates to an int) and then one and then ten. Up to that point you have a numerical value (an int) that then will be "summed" to a String. Try something like this:
String output = "" + h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
In this second case your expression will start with a String object, evaluating the rest of the operations as Strings.
You of course could use "" at the beginning or any other value that evaluates to String, like String.valueOf(h). In this last case you wouldn't need to use String.valueOf() for the other operands, as the first one is already a String.
You can either convert your numbers into a string using the toString or valueOf methods of the wrapper classes (guess you are not there yet), or just stuff all your primitives into the printline without the String output.
system.out.println(h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t);
All you need to look for is that there is a String in the printline statement. Meaning if you only want to print our number based datatype you can use system.out.println("" + youNumberVariable).
There would also be the option to add an empty string at the beginning of your declaration of output output = "" + theRest; to force all following values into the string like it does in the printline statement.
Most of it is not very pretty coding but will completly suffice for the learning process.
An easy and ugly way to do this would be to use String.valueOf for each numerical value.
As in:
String output = h + String.valueOf(three); // + etc...
Edit
morgano's approach is perfectly valid as well - +1 for that.
On a more general topic, you might want to use String.concat for String concatenation, or even better, a StringBuilder object.
This SO page contains a lot of info you can use on the matter.
I would use String.valueOf to explicitly cast each numeric value to String before being added. Like so:
String output = h + String.valueOf( three ) + String.valueOf( one ) + String.valueOf( ten ) + " " + "w" + String.valueOf( zero ) + "r" + String.valueOf( won ) + "d " + String.valueOf( two ) + " " + t;
The trick is to get the compiler to interpret + as string concatenation (which then silently convert the numbers to strings) instead of adding two numbers. This mean that one of the two arguments to + must be a string, and not - as your first three arguments - numbers (and yes, a char is a number).
It is not typical in code in the wild to want numbers to be directly adjacent to each other, but have a space between them, like:
String output = h + " " + three + " " + one + " " + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
If you really want to have no spaces, then just let the first argument be the empty string:
String output = "" + h ....
You could also just change h from char to String.
The result you're getting is because, essentially, you're doing arithmetical operations on numeric variable before printing them when relying on implicit casting.
Even the Char is a numeral! H has the value 72 in the ascii table, so you are basically instructing the Java program to print the result of:
72 + 3 + 1 + 10.0 (which is equal to 86.0)
String concatenation with mixed inputs of numerals and symbols like this can be problematic since implicit casting is in play.
In order to make sure stuff is as you want, without using explicit casting, maybe use either strings between each numeric value, like this:
char h = 'H'; // This is a numeral! Capital H has value 72 in Ascii table
byte three = 3;
short one = 1;
boolean t = true; // not a numeral
double ten = 10;
float two = (float) 2.0;
long lOne = 1;
int zero = 0;
System.out.println(h + "" + three + "" + one + "" + (int) ten + " w"
+ zero + "r" + lOne + "d " + two + " " + t );
Note how I needed to cast ten to the int-type, to lose the decimal...
Above example is however not a good example of using string concatenations!
For a proper solution, and this is maybe more aimed at people with more experience, is to try using String formatting, like this:
System.out.println(String.format("%s%s%s%s w%sr%sd %s %s", h, three, one,
(int) ten, zero, lOne, two, t));
Another way is to use message formatting like this, maybe not the best choice for this assignment since the float will be printed as an integer. Also needs to import java.text.MessageFormat
// please note: the double and the float won't print decimals!
// note: import java.text.MessageFormat for this
System.out.println(MessageFormat.format("{0}{1}{2}{3} w{4}r{5}d {6} {7}", h,
three, one, (int) ten, zero, lOne, two, t));
More examples from the Ascii table.
public class Main {
public static void main(String[] args) {
int b = 3110;
int d = 0;
String e = "orld";
double f = 2;
boolean g = true;
System.out.println("H" + b + " " + "w" + d + e + " " + f + " " + g);
}
}