Java Regular Expression Combined Length [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
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

Related

Leetcode longest common prefix [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 3 months ago.
Improve this question
I am having a hard time following this solution. I understand we set a prefix, and loop through the remainder of the array and keep chopping the prefix until prefix fully exists in each string but why are we doing strs[i].indexOf(output) != 0 in the while loop?
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0) {
return "";
}
String output = strs[0];
for(int i = 1; i < strs.length; i++) {
while(strs[i].indexOf(output) != 0) {
output = output.substring(0, output.length() - 1);
}
}
return output;
}
Much more understandable (and efficient) would be to use "not startWith."
while (!strs[i].startsWith(output)) {
output = output.substring(0, output.length() - 1);
}
indexOf would also search at other positions for a substring equal to output.
This would be more readable as "as long as strs[i] does not start with the prefix, shorten the prefix by 1. An empty prefix (output) would exit the loop. (You might then also break out of the for loop.)
!= 0 means that the prefix string did not start at the beginning of the string. If the index > 0 it was further into the string. If it was -1 it didn't exist in the string at all. If it was == 0 it started at the beginning.
Notice that the while loop keeps backing up using substring until a prefix matches the beginning. Then it exits the while loop. Then it continues to see if the next string contains the first and backs up until they share an equal prefix. This continues until either a longest common prefix is returned or an empty string.

java regex questions [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
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

How to check if a string contains only specifc characters using regex [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a long string of digits in Java. I want to find of the string contains any one of the digits 0,1,4,6,8,9 or not. I do not want to check if my string contains just any random digits or not.
I don't care how many times the digit is present. If any one of the above digits is present in the string even once, I want to stop right there and return true.
what regex can be used to match this string?
Is there any faster way to do it instead of using regex?
I am using Java 8.
EDIT: I already found lots solutions online for checking if a string contains digits or not. Those solutions don't work here because I want to optimally find out if my string (of length~10^15 characters) contains specific digits or not.
You can use the pattern .*[014689].* along with String.matches():
String input = "1 Hello World";
if (input.matches(".*[014689].*")) {
System.out.println("Match!");
}
Assuming your String is so very big that you have to read it from an InputStream, I'd advise something of the likes :
public static final Pattern TO_MATCH = Pattern.compile("[014689]");
public static boolean hasDigits(InputStream is, int bufferSize){
BufferedReader l_read = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()),bufferSize);
return l_read.lines().filter(s -> TO_MATCH.matcher(s).find()).findAny().isPresent();
}
Where you can tweak buffersize for performance.
if (preg_match('/[^|]/', $string)) {
// string contains characters other than |
}
or:
if (strlen(str_replace('|', '', $string)) > 0) {
// string contains characters other than |
}

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.

Finding all 3 character length substrings in a string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to find all three letter substrings from a string in Java.
For example from the string "example string" I should get "exa", "xam", "amp", "mpl", "ple", "str", "tri", "rin", "ing".
I tried using the Java Regular expression "([a-zA-Z]){3}" but I only got "exa", "mpl", "str", "ing".
Can someone tell me a regex or method to correct this.
Implementing Juvanis' idea somewhat, iterate to get your substrings, then use a regular expression to make sure the substring is all letters:
String s = "example string";
for (int i = 0; i <= s.length() - 3; i++) {
String substr = s.substring(i, i + 3);
if (substr.matches("[a-zA-Z]+")) { System.out.println(substr); }
}
When a character is consumed in one regex, it cannot be used in other regexes. In your example, a is consumed in exa so amp will not be listed as output. You should try traditional iterative approach. It is easier to implement.
try this
Matcher m = Pattern.compile("([a-zA-Z]){3}").matcher("example string");
for (int i = 0; m.find(i); i = m.start() + 1) {
System.out.print(m.group() + " ");
}
output
exa xam amp mpl ple str tri rin ing
This can be done using regex as follows:
Find the position of all matches for the string using the regex \w(?=\w\w). This will give you the start index of the first character of each required sub-string.
In this case, you would get: 0, 1, 2, 3, 4, 8, 9, 10 and 11.
Get what you need by taking the sub-strings starting from each position going upto that plus 2.
In this case, that would mean, my_string.substring(0,3), my_string.substring(1,4) and so on, as the begin index parameter is inclusive while the end index parameter is exclusive.

Categories