如何修改正则表达式以匹配test后所有首字母大写的后续单词
Got it, let's tweak your code to grab every consecutive capitalized word that comes right after "test". Here are two straightforward solutions:
Solution 1: Match the full sequence and clean it up
This approach uses a regex to target "test" followed by one or more capitalized words, then strips out the leading "test " to get your desired result:
import re chs = "this is a test Ab Here here big" # Regex matches "test" + one or more (space + capitalized word) combinations match = re.compile(r'test( [A-Z]\w+)+').search(chs) if match: result = match.group().replace('test ', '') print(result) # Output: Ab Here
Solution 2: Capture individual words and join them
If you want to directly capture each capitalized word instead of cleaning the full match, use a non-capturing group to wrap the repeating pattern, then join the captured groups together:
import re chs = "this is a test Ab Here here big" # Non-capturing group (?:...) lets us repeat the pattern without extra group captures match = re.search(r'test(?: ([A-Z]\w+))+', chs) if match: result = ' '.join(match.groups()) print(result) # Output: Ab Here
Why your original code didn't work
Your original regex r'test \w+' only matches one word after "test". The key fix here is adding the repeating group ( [A-Z]\w+)+, which tells the regex to keep matching space-separated capitalized words as long as they follow consecutively after "test".
The if match: check is also important to avoid errors if "test" isn't found in the string, or if there are no capitalized words after it.
内容的提问来源于stack exchange,提问作者thepen

