I would like to validate a value which should have numbers only and length should be 11 and should not start with 129.
Is this possible as I am not very efficient in regular expressions?
Use negative lookahead. The regex should be ^(?!129)\d{11}$ Turn that into a Java pattern; escape the backslash.
You can use
String num_regex = "^(?!129)\\b[0-9]{11}\\b";
String testString= "12345678910";
Boolean b = testString.matches(num_regex);
System.out.println("String: " + testString + " :Valid = " + b);
testString= "12945678910";
b = testString.matches(num_regex);
System.out.println("String: " + testString + " :Valid = " + b);
OUTPUT:
String: 12345678910 :Valid = true
String: 12945678910 :Valid = false
Related
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 + "].*)";
}
}
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;
}
}
I have a string
String str = "line1"+"\n" +
"line2"+"\n" +
"line3"+"\n" +
"line4"+"\n" +
"line5"+"\n" +
"line6"+"\n" +
"line7"+"\n" +
"line8"+"\n" +
"line9"+"\n" +
"line10"+"\n" +
"line11"+"\n" +
"line12"+"\n" +
"line13"+"\n" +
"line14"+"\n" +
"line15"+"\n" +
"line16"+"\n" +
"line17"+"\n";
I want to get out of it an array of strings
String str1 = "line1"+"\n" +
"line2"+"\n" +
"line3"+"\n" +
"line4"+"\n";
String str2 = "line5"+"\n" +
"line6"+"\n" +
"line7"+"\n" +
"line8"+"\n";
String str3 = "line9"+"\n" +
"line10"+"\n" +
"line11"+"\n" +
"line12"+"\n";
String str4 = "line13"+"\n" +
"line14"+"\n" +
"line15"+"\n" +
"line16"+"\n";
String str5 = "line17"+"\n";
if I do so
String[] str1 = str.split("\n");
I get an array of strings, in which only one line, and I need it for a few
instead of the string I will have the file from which I plan to read the text in a row
for splitting string with particular format you need to specify regular expression
so in your case regular expression will be ("\r\n")
Look Here
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);
}
}
I have the name of a java variable in a string. I want to replace it with the letter x. How can I do this java, and make sure that other words in the string are not replaced ?
For example, say my variable is res, and my string is "res = res + pres + resd + _res. I want the string to become x = x + pres + resd + _res.
You can use a word boundary to only capture whole words:
String s = "res = res + pres + resd + _res";
String var = "res";
System.out.println(s.replaceAll("\\b" + var + "\\b", "x"));
outputs x = x + pres + resd + _res
You can use the \b metacharacter to match a word boundary. (Bear in mind you'll need to use doule backslashes to escape this in Java.)
So you can do something like the following:
final String searchVar = "res";
final String replacement = "x";
final String in = "res = res + pres + resd + _res";
final String result = in.replaceAll("\\b" + searchVar + "\\b", replacement);
System.out.println(result);
// prints "x = x + pres + resd + _res"