简体   繁体   中英

How can I escape this string properly?

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?

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...

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM