aspose file tools*
The moose likes Java in General and the fly likes Brackets [ ] in regular expression Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Brackets [ ] in regular expression " Watch "Brackets [ ] in regular expression " New topic
Author

Brackets [ ] in regular expression

K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2409
    
    7

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


K. Tsang JavaRanch SCJP5 SCJD/OCM-JD OCPJP7 OCPWCD5
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38765
    
  23
Have you read the whole of the tutorial about regular expressions? The square brackets [] enclose alternatives or ranges.
Piet Verdriet
Ranch Hand

Joined: Feb 25, 2006
Posts: 266
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".
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Brackets [ ] in regular expression