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

求匹配固定有序单词序列的Regex表达式(可含数字分隔)

Regex Pattern for Ordered Words with Numeric Segments

Example for Two Words (my_word followed by my_other_word)

The regex below matches all your sample cases while enforcing the fixed order of words and allowing numeric segments between/after words:

^my_word(?:\.\d+)*(?:\.my_other_word(?:\.\d+)*)?$

Breakdown:

  • ^my_word: Starts with the exact first word my_word
  • (?:\.\d+)*: Optional repeated sequence of a dot followed by one or more digits (matches numeric segments after my_word)
  • (?:\.my_other_word(?:\.\d+)*)?: Optional sequence that:
    • Starts with a dot followed by the exact second word my_other_word
    • Followed by optional repeated numeric segments (dot + digits)
  • $: Ensures the string ends here (no extra characters after the last segment)

Valid Matches (Your Samples):

  • my_word
  • my_word.0
  • my_word.1
  • my_word.0.my_other_word
  • my_word.my_other_word
  • my_word.my_other_word.0

Generalizing to Any Number of Ordered Words

If you have a list of words in fixed order (e.g., W1, W2, W3, ..., Wn), the pattern follows this reusable structure:

^W1(?:\.\d+)*(?:\.W2(?:\.\d+)*(?:\.W3(?:\.\d+)*)*...(?:\.Wn(?:\.\d+)*)?)?$

Build Steps:

  1. Start with ^W1 (anchor the first word at the string start)
  2. Add (?:\.\d+)* to allow any number of numeric segments after the first word
  3. For each subsequent word Wk:
    • Wrap it in (?:\.Wk(?:\.\d+)*) to require the word in order, followed by optional numeric segments
    • Make each sequence optional (add ? at the end) to allow stopping at any previous word in the list
  4. End with $ to match the full string (no extra trailing characters)

Example for Three Words (W1, W2, W3)

^W1(?:\.\d+)*(?:\.W2(?:\.\d+)*(?:\.W3(?:\.\d+)*)?)?$

This pattern will match cases like:

  • W1
  • W1.123
  • W1.W2
  • W1.456.W2.789
  • W1.W2.W3
  • W1.0.W2.W3.9

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:15:27