You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求验证ClassName.PropertyName格式的正确Regex正则表达式

Fixing Regex for ClassName.PropertyName Validation

Got it, let's sort out this regex problem for you! The issue with your original ^\w+(\.\w+)*$ is that \w includes digits and underscores, and it doesn't restrict the first character to be a letter—exactly why those invalid entries like 2Personnel.FirstName1 or Personnel.33FirstName were slipping through.

The Correct Regex

Here's a regex that enforces the proper naming convention (class/property names start with a letter, followed by letters, digits, or underscores):

^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)*$

Let's Break It Down

  • ^: Anchors the match to the start of the string
  • [A-Za-z]: Ensures the first character is an uppercase or lowercase letter (no digits/underscores allowed here)
  • [A-Za-z0-9_]*: Allows any number of letters, digits, or underscores after the first character (the * means 0 or more)
  • (\.[A-Za-z][A-Za-z0-9_]*)*: Handles optional nested property names—each segment after a dot must follow the same "letter-first" rule, and you can have zero or more of these segments
  • $: Anchors the match to the end of the string (prevents extra, invalid characters from being added)

Test Cases

  • Valid matches:
    • Personnel.FirstName ✅
    • UserProfile.EmailAddress ✅
    • OrderDetails.ShippingInfo.ZipCode ✅
  • Invalid matches that will be rejected:
    • 2Personnel.FirstName1 ❌ (starts with a digit)
    • Personnel.33FirstName ❌ (property name starts with a digit)
    • Personnel.First-Name ❌ (contains an invalid hyphen)
    • .FirstName ❌ (starts with a dot)
    • Personnel. ❌ (ends with a dot)

Optional: No Underscores Allowed

If your naming convention doesn't permit underscores, simply remove the _ from the regex:

^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z][A-Za-z0-9]*)*$

内容的提问来源于stack exchange,提问作者Slava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:34:32