Home > Backend Development > Golang > Use regular expressions in golang to verify whether input is lowercase letters

Use regular expressions in golang to verify whether input is lowercase letters

WBOY
Release: 2023-06-24 11:49:22
Original
1493 people have browsed it

In golang, it is very simple to use regular expressions to verify whether the input is lowercase letters. In this article, we will introduce how to use golang's regular expressions to achieve this function.

First, we need to import golang’s regular expression package regexp. The code is as follows:

import "regexp"
Copy after login

Next, we can use the MatchString method in the regular expression package to verify whether it is lowercase letters. The first parameter of the MatchString method is the regular expression, and the second parameter is the string to be verified. The code is as follows:

func IsLowerCase(str string) bool {
    var re = regexp.MustCompile("^[a-z]+$")
    return re.MatchString(str)
}
Copy after login

Here we define a function IsLowerCase, which receives a string as a parameter and returns a Boolean value. The regular expression "^[a-z]$" is used to match strings that start and end with lowercase letters. If the input string matches the regular expression, it returns true, otherwise it returns false.

The following is the complete code implementation:

package main

import (
    "fmt"
    "regexp"
)

func IsLowerCase(str string) bool {
    var re = regexp.MustCompile("^[a-z]+$")
    return re.MatchString(str)
}

func main() {
    var str1 = "abcde"
    var str2 = "ABCde"
    
    if IsLowerCase(str1) {
        fmt.Printf("%s is lowercase
", str1)
    } else {
        fmt.Printf("%s is not lowercase
", str1)
    }
    
    if IsLowerCase(str2) {
        fmt.Printf("%s is lowercase
", str2)
    } else {
        fmt.Printf("%s is not lowercase
", str2)
    }
}
Copy after login

When we run the above code, the following results will be output:

abcde is lowercase
ABCde is not lowercase
Copy after login

We can find that the input string "abcde" Meets the requirement for lowercase letters, while "ABCde" does not.

To summarize, we can use golang's regular expression package regexp to verify whether the input is lowercase letters, just use the MatchString method and the corresponding regular expression to complete.

The above is the detailed content of Use regular expressions in golang to verify whether input is lowercase letters. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template