正则表达式技术咨询:如何为以The开头的语句添加句号?
Got it, let's work through this together. Your goal is to append a period at the end of every phrase that starts with "The", while leaving non-"The" phrases (like "Fish swim") untouched—exactly as shown in your example.
Regex Pattern
(The\s.+?)(?=\sThe|$)
Replacement String
$1.
How This Works
Let's break down the regex step by step to make sure you understand it:
(The\s.+?): This is a capturing group that targets the full "The"-led phrase.Thematches the literal starting word.\scaptures the space immediately after "The"..+?is a non-greedy match: it grabs all characters until it hits our stopping condition (so it doesn't accidentally include multiple phrases).
(?=\sThe|$): This positive lookahead tells the regex where to stop matching:\sThemeans "a space followed by another 'The'" (the start of the next target phrase).$means "the end of the entire text".
Testing with Your Example
Original text:
"The car is blue The house is yellow Fish swim The fire truck is red"
The regex will match three segments:
- "The car is blue"
- "The house is yellow"
- "The fire truck is red"
After replacement, you'll get:
"The car is blue. The house is yellow. Fish swim The fire truck is red."
This works perfectly for your given case. If you ever run into edge cases (like phrases with internal "The" words), we can adjust the regex further—but for now, this should solve your problem.
内容的提问来源于stack exchange,提问作者Jens Hennersdorf

