Click here to Skip to main content
15,886,693 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Team,

I am new to perl script and using regex to validate a user input for fixed format.I have t accept only two formats of string as input.

Format 1# R99.999 {Upto any number but it should start with R and go upto some digits after decimal}

Format 2# ABCHD1234_GHI123_XYZ123_R99.999 {Any character upper and lower case with number and underscores before R99.999 will be there always}

Anything other than that will make script to fail.

What I have tried:

I have written below piece of code but getting error.

#! /usr/bin/perl -w

my $usage = "Usage : $0 <user input is required>

# Validation of user input

if (($dest !~ /^R\d+\.\d/) || ($dest !~ "/^[\w_]+/R\d+\.\d/")){
die "ERROR: $dest is not a valid input";
} esle {
     print " $dest is correct";
}


I got error like-
Search pattern not rterminated at ./MyTest.pl line

Note- if ($dest !` /^R\d+\.\d/)    this works alone to validate input like R99.999 but we need to validate both formats
Posted
Updated 26-Aug-20 9:01am
Comments
Peter_in_2780 26-Aug-20 7:42am    
if (($dest !~ /^R\d+\.\d/) || ($dest !~ "/^[\w_]+/R\d+\.\d/")){

Just before the second R you have a spurious /
JaanVvk 26-Aug-20 8:08am    
So you are suggesting to remove '/' before second R?
JaanVvk 26-Aug-20 8:15am    
When I removed it it throws another error like-

if (($dest !~ /^R\d+\.\d/) || ($dest !~ "/^[\w_]+R\d+\.\d/")){

Error- Backslash found where operator expected at near "R\"
Unquoted string "d" may clash with future reserved word
Syntax error near "R".

I need to combine these two regex, so that if any input which negate expected Formats 1 & 2 makes script to fail

1 solution

Your logic is backwards. When A != B || A != C then this will evalutate to true unless B == C
A = 2
B = 2
C = 3
A != B  => false
A != C  => true
false || true => true

You want to use && instead.

You also might want to check your regexes:
1) the match expression should not be enclosed in quotes
2) you seem to have a stray backslash before the R in the second clause
3) There's no right-hand anchor ($) for either term, so it will match R99.9a. For example your simple case would be /^R\d+\.\d+$/
4) \w includes the underscore, so you don't need to add it to the character class
5) Although you don't say so, you may need to start the complex pattern with a letter. In this case the pattern should start with /^[A-Za-z]...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900