求匹配固定有序单词序列的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 wordmy_word(?:\.\d+)*: Optional repeated sequence of a dot followed by one or more digits (matches numeric segments aftermy_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)
- Starts with a dot followed by the exact second word
$: Ensures the string ends here (no extra characters after the last segment)
Valid Matches (Your Samples):
my_wordmy_word.0my_word.1my_word.0.my_other_wordmy_word.my_other_wordmy_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:
- Start with
^W1(anchor the first word at the string start) - Add
(?:\.\d+)*to allow any number of numeric segments after the first word - 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
- Wrap it in
- 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:
W1W1.123W1.W2W1.456.W2.789W1.W2.W3W1.0.W2.W3.9
内容的提问来源于stack exchange,提问作者Brendan
相关产品推荐
相关产品推荐

