正则表达式匹配特定字符串异常,请求排查修正方案
Regex Fix for Targeted Matching
Problem Analysis
The original regex fails on q.00.00.000.0.xx_0-1111 because the (?<=[^-\s]{7}) lookbehind triggers at the earliest valid position (right after q.00.00), resulting in the match .000.0.xx_0. The intended match .0.xx_0 would be captured by the first lookbehind ((?<=[^-\s]{4}.\d{3})), but regex prioritizes leftmost matches, so the earlier, incorrect match is selected.
Corrected Regex
(?:(?<=\.\d{3})[^-]+(?=-))|(?:(?!.*?\.\d{3}(?=-))(?<=[^-\s]{7})[^-]+(?=-))|(?<=-)[^-\s]+-
Key Changes
First Segment:
(?<=\.\d{3})[^-]+(?=-)- Captures text immediately after a dot followed by three digits, up to the next hyphen. This directly targets the desired
.0.xx_0in the problematic string.
- Captures text immediately after a dot followed by three digits, up to the next hyphen. This directly targets the desired
Second Segment:
(?!.*?\.\d{3}(?=-))(?<=[^-\s]{7})[^-]+(?=-)- Adds a negative lookahead
(?!.*?\.\d{3}(?=-))to ensure this segment only runs if there are no dot-three-digit patterns before the final hyphen. This preserves correct matching for strings without three-digit groups.
- Adds a negative lookahead
Third Segment: Unchanged, matches text between two hyphens (e.g.,
00000000-intes-00000000-1111).
Test Results
q.0.0.0.1-1111: Matches1q.0.0.0.1.tt_0-1111: Matches1.tt_0tes-00000000-1111: Matches00000000-q.00.00.000.0.xx_0-1111: Matches.0.xx_0
内容的提问来源于stack exchange,提问作者MrOldSir
相关产品推荐
相关产品推荐

