java regex questions [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Given that I have a string of number, like "12354789556", I need to check that string whether has digits from 0 to 9 at least once.
Can anyone tell me whether i can express this in regex please?

If your strings contains only digits for example "123548955664789556" then try:
System.out.println(myString.chars().distinct().count() == 10);
if your string can also contain letters for example sth like "bbb1235489556fhjerfs64789556"
System.out.println(myString.replaceAll("[^\\d]", "").chars().distinct().count() == 10);

With lookaheads :
^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)
If you want to restrict the string to digits only in addition to making sure it contains every digit :
^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)\d+$
Note that a version without lookaheads would be technically possible, but would realistically have to be crafted by code as it would have to enumerate all possible orders between digits (10! = 3628800 enumerations).

You can also do it in Java like this:
boolean containsAll = true;
for (int i = 0; i < 10; i++) {
if (!str.contains("" + i)) {
containsAll = false;
}
}
return containsAll;

A non-regex way would be to loop through the String and return false if the indexOf returns -1:
static boolean checkAll(String s, char[] allNums) {
for (int i = 0; i < allNums.length; i++) {
if (s.indexOf(allNums[i]) == -1) {
return false;
}
}
return true;
}
Example

Related

Java Regular Expression Combined Length [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to write a regular expression for a number with padding spaces. The total length is four.
For example:
( 1)
( 43)
( 232)
(1239)
What I'm currently doing is list all the four cases and combined them with "|". There should be a better way to do it.
Maybe {min, max} could do the job?
Can anyone give some help?
Edit:
With the help of you guys, I get it now. It's ^(?= *\d*$)[\d ]{4}$
Thanks a lot!
If you can't use this regex, you can use Patterns for example :
String str = "( 123)";
int paddingLength = 5;
Pattern p = Pattern.compile("\\((\\s*)(\\d*)\\)");
Matcher m = p.matcher(str);
if (m.find() && m.group(1).length() + m.group(2).length() == paddingLength) {
System.out.println("Match");
} else {
System.out.println("Not Match");
}
Or like #Mad Physicist mention in comment you can use :
if (m.find() && m.group(0).length() - 2 == paddingLength) {
If your string match the regex, and the length of the first group plus the length of the second group equal to the real length then print match, else not match

How does this return the correct output? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
public int scoreUp(String[] key, String[] answers) {
int score = 0;
for (int i = 0; i < key.length; i++) {
if (key[i] == answers[i])
score += 4;
else if (answers[i] != "?" && answers[i] != key[i])
score--;
}
return score;
}
This works on http://codingbat.com/prob/p180365 but it uses == to compare Strings instead of the equals method? How come?
How does this return the correct output?
If both the key array and the answer array uses interned strings, then == is valid for comparison.
It is a dangerous assumption to make, so programmers should always use equals() for comparing strings, even if interned is guaranteed, because such guarantee may disappear in the future, and the the subtle implicit assumption may be overlooked. Always using equals() is futureproofing the code.
if (key[i] == answers[i]) in a valid reference comparing between 2 strings,
there is no reason for the compiler to complain, in fact that can be a logically way to check if objects are the same.
if that is the right way to compare string is another question.

about comparing two strings in java and expluding repeats [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
OK lets say the secret pin is:
2236 (resident evil 2 reference)
if a person type 2200
I get a match count of 2;
But:
If the person type: 2000 or 0200, or 0020, or 0002
results says that it still matches 2 numbers.
It should only match one of the 2 number but I still get a match count of 2.
I'm currently using :
if(currentPin.indexOf(secretPin.charAt(i)) != -1)
on a loop.
UPDATE:
Assuming all the the necessary variables are declared and initialized and all scopes are closed
heres the code that does the matching
for (int i = 0; i < secretPin.length(); i++)
{
if (currentPin.indexOf(secretPin.charAt(i)) != -1)
{
System.out.println("Found");
match++;
}
}
//output:
2236 //SECRET NUMBER display
0002 //USER GUESS
Found
Found
MATCH: 2 // should only match 1 if USER GUESS only contain one number 2
Assuming the number of digits is always the same between secret pin and current pin, this simple algorithm would do the trick to retrieve the number of match :
public static void main(String[] args) {
String secretPin = "2236";
String currentPin = "6322";
int match = 0;
for (int i = 0; i < currentPin.length(); i++) {
if (secretPin.contains(String.valueOf(currentPin.charAt(i)))) {
secretPin = secretPin.replaceFirst(String.valueOf(currentPin.charAt(i)), "");
match++;
}
}
System.out.println(match);
}
"if(currentPin.indexOf(secretPin.charAt(i) != -1)" is getting a character, checks if it's != -1, and passes the boolean result to indexOf. You also have a bracket mismatch. As given this will not compile, let alone produce inaccurate output. Please paste the code you say you are able to run if you would like it reviewed.

Scope of Local Variable [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm still confused with scope of local variable
This code doesn't work because i in "i & n" is not resolved. I have identified it on for loops as int i =0. is it not enough? (This is adding nth character altogether our of string).
public String everyNth(String str, int n) {
String result = "";
for (int i = 0; i <= str.length(); i++); {
if (i%n == 0) {
result = result + str.charAt(i);
}
else {
result = result;
}
}
return result;
}
To expand on Jon Skeet's answer-worthy comment, the semi-colon at the end of for (int i = 0; i <= str.length(); i++); finishes the for-statement, and i is no longer in scope after the semi-colon.
You are a few errors:
You can remove the else{ ... } part because you don't need it.
You have a extra ';' in your for loop statement.
There is a mistake on the index of the for loop. You need to do 'i less than' str.length(), instead of i<=str.length(). Basically your for loop will try to access the full-length index of your character array, but actually it exceeds length. For example, the index for string 'hello' is 0,1,2,3,4. But "hello".length() is actually 5. If you try to access the 5th index of your string, you will see a 'java.lang.StringIndexOutOfBoundsException' exception.
Also, you want the every Nth value, you want to do (i-1)%n. Again it is because of the index issue. Try to plug in parameters in your logic and use your pencil to write down the result, and you will see why.
And of course when i==0, you don't want (0-1)%n to happen. So skip i==0 by adding 'i!=0'.
Now, the following is the working code:
public static String everyNth(String str, int n) {
String result = "";
for (int i = 0; i < str.length(); i++) {
if ((i-1)%n == 0 && i!=0)
result = result + str.charAt(i);
}
return result;
}

Any ways to find out "beautiful numbers" [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
A beautiful number is a number containing only one type of digit, such as these: 0, 4, 44, 55555, 3333.
I would like to write an android app that finds out if a number is beautiful or not.
public static boolean isBeautiful(int n) {
char targetDigit = String.valueOf(n).toCharArray()[0];
for (char currentDigit : String.valueOf(n).toCharArray()) {
if (targetDigit != currentDigit) {
return false;
}
}
return true;
}
Bonus (sorry for the late addition of the bonus, but here it is), here's how to get all beautifuls up to x:
public static List<Integer> getBeautifuls(int upTo) {
List<Integer> beautifuls = new ArrayList<>();
int next = 0;
while (upTo >= next) {
beautifuls.add(next);
if (String.valueOf(next).toCharArray()[0] == '9') {
next = Integer.valueOf(new String(new char[String.valueOf(next).length() + 1]).replace("\0", "1"));
} else {
next = next + Integer.valueOf(new String(new char[String.valueOf(next).length()]).replace("\0", "1"));
}
}
return beautifuls;
}
Repeted string algorithm based on user102008's excellent answer on this question: Simple way to repeat a String in java
Note: Using Strings to create ints is a bit hack-ish and not so fast.
Try to check how many digits the number has, for example the number has 5 digits(between 10000-99999 and >= 11111)
if(num % 11111 == 0){
//it is beautiful number
}else{
//it is not beautiful
}
This is only an example for 5 digit numbers. You can develop an algorithm for checking other num of digits. I don't know is there any algorithm created before.

Categories