简体   繁体   中英

Add quote in existing regex Java

I have this existing regex : ^[_A-Za-z0-9-+]+(\\\\.[_A-Za-z0-9-]+)*

I want to add a quote in this regex. It can be anywhere and it must be present zero or only one time.

I haven't found what I need to add to be able to do this. Someone has an idea ?

You could add the ' to both character classes and start the pattern with a positive lookahead assertion for the presence of an optional ' anywhere in the string by making what is before and after the ' optional in the lookahead.

^(?=[\w.+-]*(?:'[\w.-]+)?$)[\w+'-]+(?:\.[\w-']+)*$

Explanation

  • ^ Start of string
  • (?= Positive lookahead, assert what is on the right is
    • [\\w.+-]* Match 0+ times any of [\\w.+-]*
    • (?:'[\\w.-]+)?$ Optionally match ' and 0+ times any of [\\w.-] and assert the end of the string.
  • ) Close the lookahead
  • [\\w+'-]+ Match 1+ word chars ' or -
  • (?:\\.[\\w-']+)* Optionally repeat matching the previous preceded by a .
  • $ End of string

Regex demo

In Java

String regex = "^(?=[\\w.+-]*(?:'[\\w.-]+)?$)[\\w+'-]+(?:\\.[\\w-']+)*$";

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