javaregex

regex to match a suffix in a given string


I have a function which is supposed to validate a string to not contain the below prefix I want to match every word with

                        __test_timestamp__itemname 

some examples are as follows

                       __test_1349333576093__cellphone_modelc1
                       __test_1349333576090__macbook_model_12
public boolean isvalid(String Name){
  /*pattern match to check for suffix and return true if string starts with 
    __test_timestamp_
 */
}  

The person name in this string can vary and so will the timestamp which is in milliseconds , however the timestamp is 13 characters in length and consists of digits , the itemname can contain numbers and underscore

How do I write a function to match this pattern ? Thank you in advance for helping!


Solution

  • I'm not familiarized with java but the regex is something like this:

    ^__test_[0-9]{13}__[A-Za-z0-9_]+$
    

    ^: for start string

    [0-9]{13}: 13 numbers

    [A-Za-z0-9_]+: 1 or more Mayus/minus chars, numbers and _

    $: for end string

    https://regex101.com/r/oWBfes/2

    Edit: If you need more flexibility for the timestamp, you can set min and max like this:

    {11,13}

    ^__test_[0-9]{11,13}__[A-Za-z0-9_]+$
    

    Edit: add 100 max length:

    (?=^.{0,100}$)(^__test_[0-9]{11,13}__[A-Za-z0-9_]+$)
    

    Edit: to group last occurrence:

    (?=^.{0,100}$)^__test_[0-9]{11,13}__([A-Za-z0-9_]+)$/
    

    To catch what you want, group it with ()