如何用正则表达式捕获所有句号前的单个字母?
Hey there, let's work through this regex issue together!
Your original regex /^([^.]+)/ falls short for two key reasons: first, the ^ anchor ties it strictly to the start of the string, so it can't pick up later matches like the d in your example. Second, [^.]+ matches any sequence of characters until a period—not just single letters, which isn't what you need.
The Correct Regex
Use this global regex to reliably capture every standalone single letter immediately followed by a period:
/(?<!\S)([a-zA-Z])\./g
Breakdown of Each Component:
(?<!\S): A negative lookbehind assertion that ensures the letter isn't preceded by a non-whitespace character. This guarantees we only target single, isolated letters (not part of longer words liketest.where we'd accidentally capture thet).([a-zA-Z]): The capture group that grabs the single uppercase or lowercase letter we care about.\.: Matches the literal period right after the letter.g: The global flag, which tells the regex engine to scan the entire string for all matches instead of stopping at the first one.
Example Usage (JavaScript)
Here's how you'd extract all the captured letters in practice:
const inputStr = "a. Lorem ipsum dolor sit amet, consectetur adipiscing elit, d. Donec euismod magna velit, ac tincidunt nisl faucibus eu"; const regex = /(?<!\S)([a-zA-Z])\./g; const capturedLetters = []; let matchResult; while ((matchResult = regex.exec(inputStr)) !== null) { capturedLetters.push(matchResult[1]); } console.log(capturedLetters); // Output: ["a", "d"]
Quick Edge Case Note
This regex works seamlessly for letters at the start of the string (like your a. example) because the start of the string counts as having no non-whitespace character before it—so the lookbehind doesn't block the match.
内容的提问来源于stack exchange,提问作者Lost in google

