64

If I have a string like:

This.is.a.great.place.too.work.

or:

This/is/a/great/place/too/work/

than my program should give me that the sentence is valid and it has "work".


If I Have :

This.is.a.great.place.too.work.hahahha

or:

This/is/a/great/place/too/work/hahahah

then my program should not give me that there is a "work" in the sentence.


So I am looking at java strings to find a word at the end of the sentence having . or , or / before it. How can I achieve this?

informatik01
  • 16,038
  • 10
  • 74
  • 104
The Learner
  • 3,867
  • 14
  • 40
  • 50

6 Answers6

96

This is really simple, the String object has an endsWith method.

From your question it seems like you want either /, , or . as the delimiter set.

So:

String str = "This.is.a.great.place.to.work.";

if (str.endsWith(".work.") || str.endsWith("/work/") || str.endsWith(",work,"))
     // ... 

You can also do this with the matches method and a fairly simple regex:

if (str.matches(".*([.,/])work\\1$"))

Using the character class [.,/] specifying either a period, a slash, or a comma, and a backreference, \1 that matches whichever of the alternates were found, if any.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
pb2q
  • 58,613
  • 19
  • 146
  • 147
  • Seems like neither of these answers account for an extra char at the end like OP specified. – varatis Sep 07 '12 at 02:42
  • Thanks pb2q that answers by question as I do not know what the end character is (my issue is at the end there will be only character (,/$..)or may not be But will not be a word. so in java can u explan me what is 1$ – The Learner Sep 07 '12 at 02:59
  • 2
    @TheLearner two separate things at the regex end: the first is `\1`, which is a backreference, referring to whichever character was matched from the character set [,./] earlier in the regex; we surround that set with parens to group it as referenceable: `([,./])`. And the `$` just means _end of line_. – pb2q Sep 07 '12 at 03:00
56

You can test if a string ends with work followed by one character like this:

theString.matches(".*work.$");

If the trailing character is optional you can use this:

theString.matches(".*work.?$");

To make sure the last character is a period . or a slash / you can use this:

theString.matches(".*work[./]$");

To test for work followed by an optional period or slash you can use this:

theString.matches(".*work[./]?$");

To test for work surrounded by periods or slashes, you could do this:

theString.matches(".*[./]work[./]$");

If the tokens before and after work must match each other, you could do this:

theString.matches(".*([./])work\\1$");

Your exact requirement isn't precisely defined, but I think it would be something like this:

theString.matches(".*work[,./]?$");

In other words:

  • zero or more characters
  • followed by work
  • followed by zero or one , . OR /
  • followed by the end of the input

Explanation of various regex items:

.               --  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"

Here's a test harness to play with:

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);
    }

}
dm-kiselev
  • 177
  • 1
  • 9
jahroy
  • 22,322
  • 9
  • 59
  • 108
2

Of course you can use the StringTokenizer class to split the String with '.' or '/', and check if the last word is "work".

Makoto
  • 104,088
  • 27
  • 192
  • 230
2

You can use the substring method:

   String aString = "This.is.a.great.place.too.work.";
   String aSubstring = "work";
   String endString = aString.substring(aString.length() - 
        (aSubstring.length() + 1),aString.length() - 1);
   if ( endString.equals(aSubstring) )
       System.out.println("Equal " + aString + " " + aSubstring);
   else
       System.out.println("NOT equal " + aString + " " + aSubstring);
Scooter
  • 6,802
  • 8
  • 41
  • 64
2
    String input1 = "This.is.a.great.place.too.work.";
    String input2 = "This/is/a/great/place/too/work/";
    String input3 = "This,is,a,great,place,too,work,";
    String input4 = "This.is.a.great.place.too.work.hahahah";
    String input5 = "This/is/a/great/place/too/work/hahaha";
    String input6 = "This,is,a,great,place,too,work,hahahha";
    
    String regEx = ".*work[.,/]";
    
    System.out.println(input1.matches(regEx)); // true
    System.out.println(input2.matches(regEx)); // true
    System.out.println(input3.matches(regEx)); // true
    System.out.println(input4.matches(regEx)); // false
    System.out.println(input5.matches(regEx)); // false
    System.out.println(input6.matches(regEx)); // false
cc9999
  • 46
  • 4
  • The regular expression will make sure that the input string is ending with "work" followed by just one character, that last character should be one of the three allowed allowed characters(comma, period or the forward slash). – cc9999 Dec 28 '20 at 07:18
0

I tried all the different things mentioned here to get the index of the . character in a filename that ends with .[0-9][0-9]*, e.g. srcfile.1, srcfile.12, etc. Nothing worked. Finally, the following worked: int dotIndex = inputfilename.lastIndexOf(".");

Weird! This is with java -version:

openjdk version "1.8.0_131"
OpenJDK Runtime Environment (build 1.8.0_131-8u131-b11-0ubuntu1.16.10.2-b11)
OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)

Also, the official Java doc page for regex (from which there is a quote in one of the answers above) does not seem to specify how to look for the . character. Because \., \\., and [.] did not work for me, and I don't see any other options specified apart from these.

Sandeep Kumar
  • 2,397
  • 5
  • 30
  • 37
  • Turns out "\\." in a regex (regular expression) works, if you are looking for the dot character. The difficulty arose for me from the non-uniform API of Java String: for the task of locating/extracting the version number from a file name string, I would consider the String methods .endsWith(), .contains(), and lastly .matches. Turns out that each takes a different argument type, so things can get confusing: .endsWith(String), .contains(CharSequence), and .matches(regex)! – Intros Pector Jun 13 '18 at 06:59