Check if a string matches multiple conditions

Asked

Viewed 253 times

1

I would like to know how I do to check the following code:

if((lines[line].substr(0,2) == "N1" && lines[line].length == 94
    && lines[line].substr(3,16) == /[0-9]/
    && lines[line].substr(3,16) == "^-?\\d*\\.?\\d+$"));{

It will be read from a file and in the third condition, in positions 3 and 16 there should only be numbers from 0 to 9.

In the fourth condition, in positions 3 and 16 they cannot have numbers with signs (for example +/-) and he can’t be a number float.

I know the parts of those conditions after equality are wrong.

2 answers

4


From what I’ve seen, you want to check out the following:

  • in the first 2 positions have exactly "N1"
  • in positions 3 to 16 (i.e., 14 below), they may only have digits from 0 to 9
  • the total size of the string is 94, that is, in addition to the "N1" and of the 14 digits, they must have 78 more characters (and since you’re not checking them, I understand that they could be anything)

So you can simplify and do everything in one regex (and without having to create multiple substrings):

let regex = /^N1\d{14}.{78}$/;

["N135467897654326 shdjhsdjhsdjhsdjhjdshjsdhjdshjdshjsdhjsdhjsdhjsdhdssddssddskkdsjkdsjkdsjkdsjk",
 "N112345678909876abc"].forEach(s => {
    if (regex.test(s)) {
        console.log(`String válida: ${s}`);
    } else {
        console.log(`String inválida: ${s}`);
    }
});

The regex uses the markers ^ and $, which are respectively the beginning and the end of the string. Thus, I guarantee that the string only has what is in the regex, not a more character, not a less.

Then we have "N1", followed by \d{14}. The shortcut \d indicates a digit from 0 to 9 (but could also use [0-9], which is equivalent), and the quantifier {14} indicates "exactly 14 occurrences". That is, it is exactly 14 digits.

Then we have .{78}, which are exactly 78 characters: the dot indicates "any character, except line breaks".


In your case, simply create the regex at the beginning and for each line to test if it matches the regex:

let regex = /^N1\d{14}.{78}$/;

... para cada linha
if (regex.test(lines[line])) {
    // linha válida
}

About your code, some considerations:

  • the method substr receives 2 parameters: the initial index and the number of characters that will be taken from the initial index. Remembering that the indexes start at zero, then substr(3, 16) will pick up 16 characters, starting from the fourth character (that is, from the fourth to the nineteenth character of the string).
    • it is worth remembering that according to the documentation, substr is a legacy method and should be avoided. Instead, use substring (with the difference that this receives the initial and final index)
  • as you can see from the above code, to test whether a string corresponds to regex, you can use the method test, returning true or false (in fact you were comparing a string with regex /[0-9]/ and the other substring was being compared to the string "^-?\\d*\\.?\\d+$").
    • it is still possible to use other methods, such as exec, if it wishes to extract information from match. But as in this case you just want to know if the string corresponds to regex, use test is enough.
  • So you think it would be good for me to create, for example, if there are N2, N3, N4 Let rejex = / N1 d{14}. {78}$/; for each one?

  • 1

    @Lagaggio In the question you only put "N1", so I answered so (hence the importance of putting all the conditions very clear, as Augusto commented). Either way, if at all times is the letter "N" followed by a number, you can change to let regex = /^N\d\d{14}.{78}$/ (or let regex = /^N\d{15}.{78}$/, since in the end it will be "N" followed by 15 digits). Unless you want to check exactly what is N1, or N2, etc, then you create a regex for each. It all depends on what you want to do...

  • If I need N1 and N2 to be validated, this method would still be useful?

  • @Lagaggio As I said, if you want N1 and N2 to be checked separately, create a regex for each. If you want to validate both (ie either N1 or N2), you can use let regex = /^N[12]\d{14}.{78}$/ - the stretch [12] means "the digit 1 or digit 2" (any of them serves)

  • I have one more question, if for example in N2 will be 14 with numbers and after 14 positions I have to repeat the process of checking if there are only numbers again as I do within this model?

  • @Lagaggio I don’t understand very well, you want to only have numbers until the end of the string? Anyway, if you have another different question I recommend you to open another question, like this...) :-)

  • @Lagaggio I answered you in the chat, the regex that you put there apparently is right (with the caveats that I wrote there). Now I need to leave, until :-)

Show 3 more comments

2

Use the .test() Javascript to check if the string snippet has a character other than a number 0-9, because if there is a point, or the signs + and -, It’s not just numbers anymore.

But see that the values of your substr is incorrect. To catch the positions from 3 to 16, the correct would be lines[line].substr(2,14). The first value 2 will take the 3rd character, and the second value 14 will pick up to the 16th character. This is because the character positions in the string begin with 0 (more information on the method .substr() you find in this answer).

Returning to .test(), this method checks a string through a regex, so just use regex /[^0-9]/ to validate the string, that is, if in the string there is a character other than 0 to 9. This check must return false, therefore a sign of ! before the .test():

// EXEMPLO 1

var string1 = "N135467897654326 shdjhsdjhsdjhsdjhjdshjsdhjdshjdshjsdhjsdhjsdhjsdhdssddssddskkdsjkdsjkdsjkdsjk"; // 94 cars.

if( string1.substr(0,2) == "N1" && string1.length == 94 && !/[^0-9]/.test(string1.substr(2,14)) ){
   console.log("string1 passou");
}else{
   console.log("string1 NÃO passou");
}


// EXEMPLO 2

var string2 = "N1-3546789765326 shdjhsdjhsdjhsdjhjdshjsdhjdshjdshjsdhjsdhjsdhjsdhdssddssddskkdsjkdsjkdsjkdsjk"; // 94 cars.

if( string2.substr(0,2) == "N1" && string2.length == 94 && !/[^0-9]/.test(string2.substr(2,14)) ){
   console.log("string2 passou");
}else{
   console.log("string2 NÃO passou");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.