skip to Main Content

Since i try to used this regular expression

/names+([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*[A-Za-z0-9])(?!S)/g;

my input that i want is for example:

  1. name test
  2. name test-name
  3. name test-name-2

but when i try to check this input it’s also allowed

  1. name test-name anytext

what i want is after test-name shouldn’t allowed any whitespaces or characters anymore

5

Answers


  1. Hi maybe try something like
    names+([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*[A-Za-z0-9])(?!S)(?! )

    I added (?! ) so it means that a space is not allowed after your string

    I testes it here

    Login or Signup to reply.
  2. The regular expression for the opposite of whitespace (s) is S:

    public class main {
            public static void main(String[] args) {
                String name = "Stack Overflow is cool";
                //replace non whitespace with *
                String result = name.replaceAll("\S", "*");
                System.out.println(result);
            }
    }
    

    The output of this is "***** ******** ** ****". Note that in Java, backspaces have to be escaped.

    Login or Signup to reply.
  3. To my knowledge it is S (uppercase s). So you can try this:

    regex = /namesS+$/gm
    

    WIKIPEDIA Article for Regular Expressions

    Login or Signup to reply.
  4. Try this instead:

    /^names+([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*[A-Za-z0-9])(?:-[d]+)?$/
    

    I have checked the pattern with this test case.

    const regex = /^names+([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*[A-Za-z0-9])(?:-[d]+)?$/;
    
    const input1 = "name test";
    const input2 = "name test-name";
    const input3 = "name test-name-2";
    const input4 = "test-name ";
    
    console.log(regex.test(input1));  // Output: true
    console.log(regex.test(input2));  // Output: true
    console.log(regex.test(input3));  // Output: true
    console.log(regex.test(input4));  // Output: false
    

    I hope it works for you!

    Login or Signup to reply.
  5. names{1}+([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*[A-Za-z0-9])*(?:-+[A-Za-z0-9]+)(?!S)(?! )
    

    enter image description here
    I hope it works for you!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search