• Post Reply Bookmark Topic Watch Topic
  • New Topic

simple regex question  RSS feed

 
ben oliver
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried to create a regex pattern for "(xx)", which is bracket followed by 3 digits (first digit can't be zero), followed by another bracket. I tried and found if I write it as

\\([1-9]\\d{2}\\)

it works. But I have questions ---

1) Why it doesn't work when I put

([1-9]\\d{2}) or \([1-9]\\d{2}\) ? i.e. why do I need double backslach before that bracket char ?

2. same question for "\\d{2}", why do I need double backslach before "d{2}" ?

thanks.
 
Theodore Casser
Ranch Hand
Posts: 1902
Hibernate Netbeans IDE PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you coding your regex expressions as literal strings before you use them? It would explain the double-slashes - you're having to escape the slash to use it as part of the expression.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The regular expression itself is \([1-9]\d{2}\), because both ( and ) have special meaning in regular expressions. But remember that you are using Java strings, where \ is an escape character as well. THerefore you need to escape those \ to \\ to make sure that the string sees it as only one \.

Basically what Theodore said but in my own words
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!