我是正则表达式的新手,我正在努力想出一个匹配包含至少一个字母和零个或多个数字的单词的正则表达式。
示例:
users
- 匹配
u343sers
- 匹配
13123123
- 不匹配
我无法使用外观,因为我需要在Go中使用正则表达式,regexp
包不支持它们。
这可能没有外观吗?
答案 0 :(得分:16)
是的 - 如果没有环顾四周,可能会有110%的可能性:
(110%,我的意思是它100%可能,10%可能你能够以任何其他方式解决这个问题:D)
这样可行:
\w*[a-zA-Z]\w*
<强>解释强>
\w
:任何字母或数字,*
:0次或更多次[a-zA-Z]
:任何字母,A-Z,上限A-Z
或小写a-z
\w
:任何字母或数字,*
:0次或更多次<强> Regexper:强>
在线演示:
答案 1 :(得分:6)
答案 2 :(得分:3)
如果您使用的是Java,则所需的正则表达式为[\\p{L}0-9]*\\p{L}[\\p{L}0-9]*
说明:
\p{L}
匹配任何单个字母(例如A-Za-z,希腊语,德语等语言环境的字母)[\\p{L}0-9]*
与任意数量的字母或数字匹配,因为quantifier *
应用于由字母和数字组成的character classes上。[\\p{L}0-9]*\\p{L}[\\p{L}0-9]*
表示任何字母或数字 + 单个字母 + 任何字母或数字 > 选中java.util.regex.Pattern
,以了解有关这些模式的更多信息。
演示:
public class Main {
public static void main(String[] args) {
String[] testStrings = { "A1ö1", "_a_", "1Ωω2", "123", "1", "a", "abc", "ABC", "aBc123", "123abc", "123abc123",
"aBc123aBc", "_123", "123_", "123_123", "1_a", "_", "a_", "a_1.", "123.a", "12.56" };
for (String s : testStrings) {
System.out.println(s.matches("[\\p{L}0-9]*\\p{L}[\\p{L}0-9]*") ? s + " matches" : s + " does not match");
}
}
}
输出:
A1ö1 matches
_a_ does not match
1Ωω2 matches
123 does not match
1 does not match
a matches
abc matches
ABC matches
aBc123 matches
123abc matches
123abc123 matches
aBc123aBc matches
_123 does not match
123_ does not match
123_123 does not match
1_a does not match
_ does not match
a_ does not match
a_1. does not match
123.a does not match
12.56 does not match