如何编写bash函数isInRequiredFormat校验指定格式字符串?
Bash Function to Validate String Format for
exerciseNumber{N}Published To check if a string follows the exact format exerciseNumber{N}Published (where {N} is a natural number), you can use bash's built-in regular expression matching with the [[ ... =~ ... ]] operator. Here's a practical, easy-to-use implementation:
The isInRequiredFormat Function
This function takes a single string argument and returns 0 (success) if it matches the required format, or 1 (failure) otherwise. By default, we assume natural numbers are positive integers (1, 2, 3, ...)—see the note below if you need to include zero.
isInRequiredFormat() { # Make sure exactly one input string is provided if [ $# -ne 1 ]; then echo "Error: Please pass exactly one string to validate." >&2 return 1 fi # Regex breakdown: # ^ = start of string (ensures no extra characters before the pattern) # exerciseNumber = literal fixed prefix # [1-9][0-9]* = positive natural number (starts with non-zero digit, followed by any number of digits) # Published = literal fixed suffix # $ = end of string (ensures no extra characters after the pattern) local pattern='^exerciseNumber[1-9][0-9]*Published$' # Run case-sensitive regex match if [[ "$1" =~ $pattern ]]; then return 0 # String is in valid format else return 1 # String does NOT match the format fi }
Key Notes
- Exact Match Guarantee: The
^and$anchors ensure the entire string must fit the pattern—no partial matches or extra characters allowed. - Natural Number Flexibility: If you consider 0 a valid natural number here, replace the regex pattern with
^exerciseNumber[0-9]+Published$(this allows one or more digits, including zero). - Case Sensitivity: Bash regex is case-sensitive by default, so this function will only match strings with exact casing (
exerciseNumberwith a capital N,Publishedwith a capital P).
Usage Examples
Test the function with valid and invalid inputs to see how it works:
# Valid test cases isInRequiredFormat "exerciseNumber1Published" && echo "Valid" || echo "Invalid" # Output: Valid isInRequiredFormat "exerciseNumber42Published" && echo "Valid" || echo "Invalid" # Output: Valid isInRequiredFormat "exerciseNumber1000Published" && echo "Valid" || echo "Invalid" # Output: Valid # Invalid test cases isInRequiredFormat "exerciseNumber0Published" && echo "Valid" || echo "Invalid" # Output: Invalid (using positive natural number pattern) isInRequiredFormat "ExerciseNumber1Published" && echo "Valid" || echo "Invalid" # Invalid (capital E) isInRequiredFormat "exerciseNumberPublished" && echo "Valid" || echo "Invalid" # Invalid (missing number) isInRequiredFormat "exerciseNumber123published" && echo "Valid" || echo "Invalid" # Invalid (lowercase p) isInRequiredFormat "fooexerciseNumber1Publishedbar" && echo "Valid" || echo "Invalid" # Invalid (extra text at start/end)
内容的提问来源于stack exchange,提问作者AskMath
相关产品推荐
相关产品推荐

