正则表达式修改需求:仅捕获[a-zA-Z]匹配内容
Fixing Your Regex to Capture Only the Target Word
Hey there! Let's tweak your regex so it only captures the word after "I'm" or "I am", and fix a couple of small oversights in the original pattern.
Updated Regex
/(?:i'm|i am) ([a-zA-Z]+)/i
Breakdown of the Changes:
(?:i'm|i am): This is a non-capturing group (?:tells the regex engine not to save this prefix as a capture group). It matches either "I'm" or "I am" without cluttering your final result with these phrases.([a-zA-Z]+): This is the capturing group you care about. The+ensures it matches one or more letters—fixing the original issue where[a-zA-Z]only grabbed a single character (so it would have pulled just "s" from "sam" instead of the full word)./i: The case-insensitive modifier stays, so it works seamlessly with inputs like "I'm Sam", "I AM GOOD", etc.
Test Case Results:
- Input:
"I'm sam"→ Capture group 1 returns"sam" - Input:
"I am good at this"→ Capture group 1 returns"good"
Optional Optimizations
If you need to handle edge cases like names with hyphens or apostrophes (e.g., "O'Neil", "Mary-Ann"), expand the character set to include those valid characters:
/(?:i'm|i am) ([a-zA-Z'-]+)/i
This will correctly capture words like "O'Neil" instead of stopping at the apostrophe.
内容的提问来源于stack exchange,提问作者Ben Rivers
相关产品推荐
相关产品推荐

