您可以测试字符串是否以工作结尾,后跟一个字符,如下所示:
theString.matches(".*work.$");
如果尾随字符是可选的,则可以使用以下字符:
theString.matches(".*work.?$");
要确保最后一个字符是句点或斜杠,您可以使用以下命令:.
/
theString.matches(".*work[./]$");
要测试后跟可选句点或斜杠的工作,您可以使用以下命令:
theString.matches(".*work[./]?$");
要测试被句点或斜杠包围的工作,您可以执行以下操作:
theString.matches(".*[./]work[./]$");
如果工作前后的令牌 必须相互匹配,则可以执行以下操作:
theString.matches(".*([./])work\\1$");
您的确切要求没有精确定义,但我认为它将是这样的:
theString.matches(".*work[,./]?$");
换句话说:
- 零个或多个字符
- 其次是工作
- 后跟零或一个 OR
,
.
/
- 后跟输入的结尾
各种正则表达式项的说明:
. -- 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);
}
}