通用
如果你想设计一个通用的表达式,也许你可以从一些类似的表达式开始,
\S*the[^o\s]*\b
我猜这取决于你想要匹配和不匹配的内容。
非通用
我猜你可以简单地找到有助于解决你的问题的单词边界 (\b),用一些类似于,
\b[Tt]he\b|\b[Tt]hen\b|\bextratheaterly\b
或者,
\b(?:[Tt]hen?|[Ee]xtratheaterly)\b
Java 测试
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "\\b(?:[Tt]hen?|[Ee]xtratheaterly)\\b";
final String string = "If the world says that theo is not oreo cookies then thetatheoder is extratheaterly good.\n\n"
+ "If The world says that theo is not oreo cookies Then thetatheoder is Extratheaterly good.\n\n"
+ "If notthe world says that theo is not oreo cookies notthen thetatheoder is notextratheaterly good.\n\n\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
输出
Full match: the
Full match: then
Full match: extratheaterly
Full match: The
Full match: Then
Full match: Extratheaterly
Python 测试
import re
string = '''
If the world says that theo is not oreo cookies then thetatheoder is extratheaterly good.
If The world says that theo is not oreo cookies Then thetatheoder is Extratheaterly good.
If notthe world says that theo is not oreo cookies notthen thetatheoder is notextratheaterly good.
'''
expression = r'\b(?:[Tt]hen?|[Ee]xtratheaterly)\b'
print(re.findall(expression, string))
print([m.group(0) for m in re.finditer(expression, string)])
输出
['the', 'then', 'extratheaterly', 'The', 'Then', 'Extratheaterly']
['the', 'then', 'extratheaterly', 'The', 'Then', 'Extratheaterly']
如果您希望简化/修改/探索表达式,在regex101.com 的右上角面板中已对此进行了说明。如果您愿意,您还可以在 this link 中观看它如何与一些示例输入匹配。
正则表达式电路
jex.im 可视化正则表达式: