-1

I'm kinda a newbie to this regular expression thing. I am trying to write a regular expression to match an identifier that follows these rules:

It must begin with a letter and can have only letters, digits and underscores. The identifier must also end with a letter and must not have two consecutive underscores.

I've tried to come up with the regex for this but I haven't had much success. I need help.

2 Answers2

1

Use regex pattern

\b[a-zA-Z](?:[a-zA-Z\d]|(?<!_)_(?!_))*[a-zA-Z]\b

If you want to add also minimum and maximum length (for example min. 6 and max. 12), then use

\b(?=\w{6,12}\b)[a-zA-Z](?:[a-zA-Z\d]|(?<!_)_(?!_))*[a-zA-Z]\b
Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • @user1691402 - If you want to verify if input contains **ONLY** such "legal identifier name", then use regex pattern `^[a-zA-Z](?:[a-zA-Z\d]|(?<!_)_(?!_))*[a-zA-Z]$` for no size limitation identifier names and regex pattern `^(?=\w{6,12}$)[a-zA-Z](?:[a-zA-Z\d]|(?<!_)_(?!_))*[a-zA-Z]$` for min/max limitation names. – Ωmega Sep 22 '12 at 20:24
0

Here is a sample that I could do

public static void main(String[] args) {
    System.out.println(test("a"));
    System.out.println(test("a_a"));
    System.out.println(test("a2_f"));
    System.out.println(test("a_2f"));
    System.out.println(test("a2_fasd"));
    System.out.println(test("dsads_dsadsa"));
    System.out.println(test("d_sads_dsads_a"));
    System.out.println(test("a2_3241_4324_2f"));
    //fails
    System.out.println(test("2_3241_4324_2f"));
    System.out.println(test("a2_3241__4324_2f"));
    System.out.println(test("_dsads_dsadsa"));
    System.out.println(test("dsads_dsadsa_"));
}

//validation
public static boolean test(String name) {
    String regEx = "^[a-zA-Z](_?[a-zA-Z0-9]+)*_?[a-zA-Z]$||^[a-zA-Z]([a-zA-Z0-9]+_?)*[a-zA-Z]$||^[a-zA-Z]_[a-zA-Z]$||^[a-zA-Z]$";
    return Pattern.matches(regEx, name);
}

------------------------
Printed results
true
true
true
true
true
true
true
true
false
false
false
false
Danilo Coppi
  • 51
  • 1
  • 3