次のように、文字列がworkで終わり、その後に1文字が続くかどうかをテストできます。
theString.matches(".*work.$");
末尾の文字がオプションの場合は、次を使用できます。
theString.matches(".*work.?$");
最後の文字がピリオド.
またはスラッシュであることを確認するには、/
次を使用できます。
theString.matches(".*work[./]$");
オプションのピリオドまたはスラッシュが続く作業をテストするには、次を使用できます。
theString.matches(".*work[./]?$");
ピリオドまたはスラッシュで囲まれた作業 をテストするには、次のようにします。
theString.matches(".*[./]work[./]$");
作業の前後 のトークンが互いに一致する必要がある場合は、次のようにすることができます。
theString.matches(".*([./])work\\1$");
正確な要件は正確に定義されていませんが、次のようになると思います。
theString.matches(".*work[,./]?$");
言い換えると:
- 0文字以上
- 仕事が続く
- ゼロまたは1つの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);
}
}