-1

i have this Regex in my Java program

if(Function.match(strAddress, "[~|+_=!$%^*@`(){}:;\"'<>?,]++"))
--do something

I want to include [ and ] in regex as well. I tried using escape characters as well but no go. How do I add these characters to my regex?

Use this example

public class test {

    public static void main(String[] args) {
        String text = "asda[]";
        System.out.println("Test: "+ text.matches("[~|+_=!$%^*@`(){}:;\"'<>?,\\[\\]]++"));
    }
}

I tried with \[ and [, its not working

Last run on above code gave output Test: false

YCF_L
  • 51,266
  • 13
  • 85
  • 129
uSeruSher
  • 790
  • 8
  • 26

1 Answers1

2

try to use :

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

You have to escape this two character with \\

Edit

of course it match only this group of characters

~|+_=!$%^*@`(){}:;\"'<>?,[]

but in your example you are using alphabetic, so instead you have to include a-z for lower character, and A-Z to matches also the upper characters :

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

Now for your example :

String text = "asda[]";
System.out.println("Test: " + text.matches("[a-z~|+_=!$%^*@`(){}:;\"'<>?,\\[\\]]++"));

it return:

Test: true

EDIT

You can go with this solution :

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

which will gives you :

abc[]  -> true
[]     -> true
abc    -> false
[]abc  -> false
YCF_L
  • 51,266
  • 13
  • 85
  • 129