[java] Check if string ends with certain pattern

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?

This question is related to java regex string pattern-matching

The answer is


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


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.


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

}

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.


    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

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to pattern-matching

How to select lines between two marker patterns which may occur multiple times with awk/sed Check if string ends with certain pattern Ruby Regexp group matching, assign variables on 1 line Pattern matching using a wildcard How to find a whole word in a String in java Count character occurrences in a string in C++ How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?