0

I have a complex regex I want to apply. Here is my pattern:

/(?:^|\s|[\.(\+\-\,])(?:\$?)\$((?:[0-9]+(?=[a-z])|(?![0-9\.\:\_\-]))(?:[a-z0-9]|[\_\.\-\:](?![\.\_\.\-\:]))*[a-z0-9]+)/i

How can I declare this as a String and make sure everything is escaped?

4
  • 1
    Step one: Simplify you pattern by getting rid on unnecessary backslashes and groups: /(?:^|[\s.(+,-])\$?\$((?:[0-9]+(?=[a-z])|(?![0-9.:_-]))(?:[a-z0-9]|[.:_-](?![.:_-]))*[a-z0-9]+)/i
    – Gumbo
    Nov 22, 2010 at 18:06
  • Do you have any issues with Pattern.quote()?
    – bcosca
    Nov 22, 2010 at 18:10
  • @Gumbo: Who says it is unnecessary? If he has to replace one of the groups, he really need groups. Nov 22, 2010 at 19:14
  • 1
    @Martijn Courteaux: (?:\$?) is unnecessary.
    – Gumbo
    Nov 22, 2010 at 20:23

3 Answers 3

2

It looks to me as if there's a lot of unnecessary stuff in that regex

  1. Something like (?:\$?) is the same as just \$?
  2. There's no need to "protect" the ".", "_", ",", or "+" characters in a square-bracket group

So what you really could have is:

/(?:^|\s|[.(+\-,])\$?\$((?:[0-9]+(?=[a-z])|(?![0-9.:_\-]))(?:[a-z0-9]|[_.\-:](?![._\-:]))*[a-z0-9]+)/i

As for putting it in a string, all you really have to worry about here are the backslashes. Those need to be doubled ("\"). The outer "/" characters would be dropped, and the trailing "i" modifier would be passed into the Pattern.compile() method.

2

As long as a somewhat static solution will suffice, and if you are using Eclipse IDE you can choose to have String escaped correctly when pasting from clipboard.

Preferences -> Java -> Editor -> Typing -> [x] Escape text when pasting...

0

If you're trying to test that pattern, I suggest you look into using a regex tool like gskinner. It lets you put in a pattern, a string, and highlights the matches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.