英文:
Regex match cellphone number from string
问题
我想从字符串中匹配正确的电话号码。例如:
string := "my phone number is 15817452367"
re := regexp.MustCompile(`1[34578][0-9]{9}`)
re.FindAllString(string, -1)
-> 15817452367
这个结果是正确的,但对于另一个字符串:
string := "my card number is 115817452367"
re := regexp.MustCompile(`1[34578][0-9]{9}`)
re.FindAllString(string, -1)
-> 15817452367 (无效)
这个正则表达式也匹配了电话号码,但我不希望从数字字符串中获取电话号码。我该如何修复这个正则表达式?提前感谢!
英文:
I want to match the right phone number from a string. For example:
string := "my phone number is 15817452367"
re := regexp.MustCompile(`1[34578][0-9]{9}`)
re.FindAllString(string, -1)
-> 15817452367
This result is right, but for another string:
string := "my card number is 115817452367"
re := regexp.MustCompile(`1[34578][0-9]{9}`)
re.FindAllString(string, -1)
-> 15817452367 (invalid)
This regex also matches the phone number, but I want this to not be a valid value,I don't want to get a phone number form a digital string. How can I fix the regex? Thanks in advance!
答案1
得分: 3
你可以检查正则表达式的开头和结尾,以确定字符串的开头/结尾或非数字字符,并且只捕获电话号码。
以下是一个工作正则表达式的示例:
(?:^|[^0-9])(1[34578][0-9]{9})(?:$|[^0-9])
在 Golang 中的使用示例:
re := regexp.MustCompile(`(?:^|[^0-9])(1[34578][0-9]{9})(?:$|[^0-9])`)
submatch := re.FindStringSubmatch("Phone Number: 15817452367;")
if len(submatch) < 2 {
// 未找到匹配项
}
match := submatch[1]
解释:
找到字符串的开头或非数字字符,放在非捕获组中:
(?:^|[^0-9])
找到要搜索的电话号码,放在捕获组中:
(1[34578][0-9]{9})
找到字符串的结尾或非数字字符,放在非捕获组中:
(?:$|[^0-9])
英文:
You can check the beginning and end of the regex for the beginning/end of the string or a non-digit character and only capture the phone number.
Here is some working Regex as an example:
(?:^|[^0-9])(1[34578][0-9]{9})(?:$|[^0-9])
In Golang
re := regexp.MustCompile(`(?:^|[^0-9])(1[34578][0-9]{9})(?:$|[^0-9])`)
submatch := re.FindStringSubmatch("Phone Number: 15817452367;")
if len(submatch) < 2 {
// No match found
}
match := submatch[1]
Explanation:
Find the start of the string or a non-digit character.
Enclosed in non-capture group.
(?:^|[^0-9])
Find the phone number you are searching for.
Enclosed in capture group.
(1[34578][0-9]{9})
Find the end of the string or a non-digit character.
Enclosed in non-capture group.
(?:$|[^0-9])
答案2
得分: 0
你可以检查匹配的字符串前后是否没有数字。
为了检查这一点,将你的模式嵌套在两个[^0-9]*
之间:它表示“没有或不是数字”。
regexp.MustCompile(`[^0-9]*1[34578][0-9]{9}[^0-9]*`)
这样,15817452367
将被检测为匹配,但115817452367
将不会。
英文:
You can check if the matched string is not preceded nor followed by digits.
In order to check this, nest your pattern between two [^0-9]*
: it means "nothing or not a digit".
regexp.MustCompile(`[^0-9]*1[34578][0-9]{9}[^0-9]*`)
This way, 15817452367
will be detected as a match, but 115817452367
will not.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论