1
  1. My Requirement is "Name should begin with an alphabet and should have atleast three chars and cannot end with a special character,But the special chars can come in the middle ." It should not allow underscore at the end also.
  2. Regex that I am using [a-zA-Z][\w]{1,}.*[\w]
  3. The above regex not recognise underscore(_) as special char at the end.
  4. when I type "sss_" its not recognising.
  5. when i type "sss@" or "sss#" or "sss$" its recognising.

  6. The expected result "test", "test@test", "test_test", "tes"

  7. unexpected result "tes@", "test_", "te"

Sabarinathan
  • 439
  • 1
  • 7
  • 19

2 Answers2

1

Update 2:

Since you now say it is in Android, remove (?U). All shorthand character classes are already Unicode-aware in the Android regex:

"\\p{L}+(?:[\\W_]\\p{L}+)*"

And use it with matches().

Updated answer

Use

Boolean isValid = groupNameString.matches("(?U)\\p{L}+(?:[\\W_]\\p{L}+)*");

See the online Java demo.

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(validateName("Dąb_rośnie$gdzieś#tu"));
        System.out.println(validateName("Some_string_here"));
    }
    private static boolean validateName(String name) { 
        if (name.matches("(?U)\\p{L}+(?:[\\W_]\\p{L}+)*")) { 
            return true; 
        } 
        return false; 
    } 
}

Note you do not even need anchors when using String#matches() since this method anchors the pattern by default.

The [\\W_] will match any special char inlcuding a _.

Original answer

To match the letters + ( _ + letters) * pattern, you may use

 ^[^\W\d_]+(?:_[^\W\d_]+)*$

Instead of [^\W\d_], you may use [a-zA-Z] in JS or any other engine that is not Unicode-aware and you need to handle ASCII letters only.

The Unicode-aware equivalent:

^\p{L}+(?:_\p{L}+)*$

Here, \p{L} matches any Unicode letter.

Details:

  • ^ - start of string anchor
  • [^\W\d_]+ / \p{L}+ - 1 or more letters
  • (?:_[^\W\d_]+)* - zero or more occurrences of:
    • _ - a _
    • [^\W\d_]+ / \p{L}+ - 1 or more letters
  • $ - end of string anchor.

See this regex demo.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/138401/discussion-on-answer-by-wiktor-stribizew-regular-expression-for-not-allowing-spe). – Bhargav Rao Mar 18 '17 at 15:45
0

Try this regex expression

^[A-z]+[^\`|\~|\!|\@|\#|\$|\%|\^|\&|\_|\*|\(|\)|\+|\=|\[|\{|\]|\}|\||\\|\'|\<|\,|\.|\>|\?|\/|\""|\;|\:|\s]+$