Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Brackets [ ] in regular expression

 
K. Tsang
Bartender
Posts: 3397
13
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
I have a questions regarding using regular expressions. When do I use the brackets [] to enclose the regex?

Suppose I want ONLY n,y,N,Y then the regex is [nyNY] or [\w&&[nyNY]] works fine. Using the first regex in Sun Java Tutorial RegexTestHarness program I got:

Enter your regex: [nyNY]
Enter input string to search: n
I found the text "n" starting at index 0 and ending at index 1

Enter your regex: [nyNY]
Enter input string to search: y
I found the text "y" starting at index 0 and ending at index 1

Enter your regex: nyNY
Enter input string to search: n
No match found

Enter your regex: nyNY
Enter input string to search: y
No match found

Enter your regex: nyNY
Enter input string to search: ny
No match found

Enter your regex: nyNY
Enter input string to search: nyNY
I found the text "nyNY" starting at index 0 and ending at index 4


My question is once I remove the brackets why it only return a match if I type exactly as it (eg "nyNY")? What's the purpose of those []?

Thanks
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you read the whole of the tutorial about regular expressions? The square brackets [] enclose alternatives or ranges.
 
Piet Verdriet
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question is once I remove the brackets why it only return a match if I type exactly as it (eg "nyNY")? What's the purpose of those []?


As you already saw: [nyNY] matches only one character: 'n', 'y', 'N' or 'Y' while nyNY matches the complete String "nyNY".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic