简体   繁体   中英

Regex to match string either not exact string or pattern

I'm trying to match a pattern with this regex

"^[a-zA-Z]{1}[a-zA-Z0-9\\s_]*(?<![Ii][Dd]|[Cc][Rr][Ee][Aa][Tt][Ee][Dd][Dd][Aa][Tt][Ee]|[Cc][Rr][Ee][Aa][Tt][Ee][Dd][Bb][Yy]|[Mm][Oo][Dd][Ii][Ff][Ii][Ee][Dd][Dd][Aa][Tt][Ee]|[Mm][Oo][Dd][Ii][Ff][Ii][Ee][Dd][Bb][Yy]|[Oo][Rr][Gg][Ii][Dd])$"

This pattern should match any string that does not start with a number or has anything else other than space, underscore, characters and numbers along with that it should also fail if the string is exactly ID or CreatedDate or CreatedBy or ModifiedDate or ModifiedBy or OrgID . It should also check that the static strings are checked without case sensitivity.

  • Pass - "Bob9 Tom"
  • Fail - "9Bob Tom"
  • Fail - "ID"
  • Pass - "Tom Tom"
  • Pass - "Tom ID"
  • Pass - "IDTom"
  • Pass - "TomID"

You need to add a negative lookahead at the start to check for the string which won't contain the exact string mentioned. (?i) called case-insensitive modifier which forces the regex engine to do a case-insensitive match.

@"(?i)^(?!(?:ID|CreatedDate|CreatedBy|ModifiedDate|ModifiedBy|OrgID)$)[a-zA-Z][a-zA-Z0-9\s_]*"

DEMO

This pattern should match any string

  • that does not start with a number

     ^\\D 
  • or has anything else other than space, underscore, characters and numbers

     ^\\D[ _a-zA-Z0-9]*$ 
  • along with that it should also fail if the string is exactly ID or CreatedDate or CreatedBy or ModifiedDate or ModifiedBy or OrgID .

     ^(?!(?:CreatedDate|CreatedBy|ModifiedDate|ModifiedBy|OrgID)$)\\D[ _a-zA-Z0-9]*$ 
  • It should also check that the static strings are checked without case sensitivity.

     ^(?!(?:(?i)CreatedDate|CreatedBy|ModifiedDate|ModifiedBy|OrgID)$)\\D[ _a-zA-Z0-9]*$ 

Notes

  • The last step could be substituted by making the entire regex case-insensitive.
  • ^\\D literally means "should not start with a number". If you meant "...but the starting character should still be one of [ _a-zA-Z0-9] ", then ^\\D would have to change to ^[a-zA-Z] .
  • if you switch the entire expression to case-insensitive (and I don't see why you wouldn't), youc can replace all a-zA-Z with az .

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