【发布时间】:2017-06-29 13:30:41
【问题描述】:
我将 REGEX 视为解决问题的可能方法。我制作了一些示例字符串,其中包含诸如 hello、hllllooo、hhhheello 等单词。然后我创建了一个正则表达式来查找所有这些类型的单词。我不应该做的是查看可能包含或不包含输入单词的句子。例如,您输入helloloo,我想扫描我的句子以查找类似于“helloloo”的单词,如果在句子中找到则返回“hello”。我可以创建一个作为用户输入变量的正则表达式吗?如果你输入 hellloo,那么我会构造一些东西,从句子或文件中返回相似的词。
两个输入字符串
String line = "this is hello helloooo hellllooo hhhel hellll what can I do?";
String longLine = "hello man this what can up down where hey my there find now ok stuff jive super sam dude car";
我的正则表达式函数
public static void regexChecker(String theRegex, String str2Check) {
Pattern checkRegex = Pattern.compile(theRegex);
Matcher regexMatcher = checkRegex.matcher(str2Check);
while(regexMatcher.find()) {
if(regexMatcher.group().length() != 0) {
System.out.println(regexMatcher.group().trim());
}
}
}
运行这个
regexChecker("\\s[h]*[e]*[l]*[l]*[o]*\\s", line);
返回
hello
hello
hellllooo
hellll
我想根据用户输入“helllooo”创建一个正则表达式,它从第二个字符串 longLine 返回 hello。不确定正则表达式是否是正确的解决方案,但我想知道它是否可能。
【问题讨论】:
-
你为什么把这些字母放在
[]?别。 --- 你真的希望这些字母是可选的,所以它匹配例如ho这个词?将*更改为+以要求每个字母中至少有一个。 --- 将\\s都替换为\\b以匹配单词边界。 --- 正则表达式应该是"\\bh+e+l+l+o+\\b"。请参阅regex101 进行演示。 -
谢谢,应该是+