Thursday, March 31, 2011

Regex to find special characters from a String with some exceptions

I need to write a small regex which should match the occurrences of literal character * when it appears with any other special character. For example, I need to catch all of these occurrences !* )* (* ** *.* . The exception to this is *= and =*, which I want to allow. I tried writing the regex as

\W&&[^=]\*|\*\W&&[^=]

but this doesn't seem to work. Any suggestions? Thanks much for the help.

From stackoverflow
  • That one matches all your bad samples:

    (\!\*|\)\*|\(\*|\*\*|\*\.\*)
    

    If you want more than these 4 cases, describe a bit better, what to allow and what to forbid.

    arya : Thanks Johannes for the response. But I was looking for a generic regex which works for any special character. It should catch all of the combination except *= and =*
    arya : Any occurrences of special characters which involve a * are to be caught. Only exception is *= and =*
    Johannes Weiß : define special character
    arya : anything which falls under \W Thanks.
    Johannes Weiß : ah ok, perl regex. Which library do you use? Perl itself?
    arya : I'm using this with Java pattern class
  • I think you're looking for a regex with lookbehind and lookahead assertions. Something like:

    (?!=[\=\s])\*(?![\=\s])
    
  • try this

    ([^(\W\*)*(\*\W)*]|=\*|\*=)
    
    arya : It works just opposite. It catches nothing but =* and *=
  • (\*[^\w=]|[^\w=]\*)
    

    That matches a asterisk followed by any non-word character (other than an equals sign), or a non-word character followed by an asterisk/

    arya : Thanks tj111. That works perfect.

0 comments:

Post a Comment