您可以测试一个字符串是否以work结尾,后跟一个字符,如下所示:
theString.matches(".*work.$");
如果尾随字符是可选的,您可以使用:
theString.matches(".*work.?$");
要确保最后一个字符是句点.
或斜杠/
,您可以使用:
theString.matches(".*work[./]$");
要测试后跟可选句点或斜线的工作,您可以使用以下命令:
theString.matches(".*work[./]?$");
要测试被句点或斜线包围的工作 ,您可以这样做:
theString.matches(".*[./]work[./]$");
如果工作前后的令牌 必须相互匹配,您可以这样做:
theString.matches(".*([./])work\\1$");
您的确切要求没有精确定义,但我认为它会是这样的:
theString.matches(".*work[,./]?$");
换句话说:
- 零个或多个字符
- 其次是工作
- 后跟零或一
,
.
或 /
- 然后是输入的结尾
各种正则表达式项目的解释:
. -- any character
* -- zero or more of the preceeding expression
$ -- the end of the line/input
? -- zero or one of the preceeding expression
[./,] -- either a period or a slash or a comma
[abc] -- matches a, b, or c
[abc]* -- zero or more of (a, b, or c)
[abc]? -- zero or one of (a, b, or c)
enclosing a pattern in parentheses is called "grouping"
([abc])blah\\1 -- a, b, or c followed by blah followed by "the first group"
这是一个可以使用的测试工具:
class TestStuff {
public static void main (String[] args) {
String[] testStrings = {
"work.",
"work-",
"workp",
"/foo/work.",
"/bar/work",
"baz/work.",
"baz.funk.work.",
"funk.work",
"jazz/junk/foo/work.",
"funk/punk/work/",
"/funk/foo/bar/work",
"/funk/foo/bar/work/",
".funk.foo.bar.work.",
".funk.foo.bar.work",
"goo/balls/work/",
"goo/balls/work/funk"
};
for (String t : testStrings) {
print("word: " + t + " ---> " + matchesIt(t));
}
}
public static boolean matchesIt(String s) {
return s.matches(".*([./,])work\\1?$");
}
public static void print(Object o) {
String s = (o == null) ? "null" : o.toString();
System.out.println(o);
}
}