0

我正在为基于位置的服务进行一些文本处理,我想找出输入是否与 type 匹配something sth FROM xxxx TO yyyy。基本上我需要找出用户输入的来源和目的地。

例如

show me how can I go from xxxx to yyyy
I want to go to abcd
I want to go from abcd to xyz

我不擅长正则表达式,我能想出的正则表达式A-Za-z来自A-Za-z哪个A-Za-z不起作用。谁能告诉我如何匹配多关键字正则表达式,其中单词可以被任意数量的单词分隔。例如I want to go FROM manhattan TO SeattleI want to go FROM times square, New York City TO Seattle。然后我可以通过索引来提取源/目标。

如果它包含FROM在句子的中间,我可以提取它,但我想让它通用,所以我不必创建多个规则。用户可能会说

I want to go TO x FROM y
I want to go FROM x to Y

在上面的句子中,源和目标被交换了。

谢谢

4

3 回答 3

2

您需要使用单词边界锚点,否则正则表达式将在句子上失败

I want to go from Montreal to Toronto.

此外,您应该捕获匹配词之间的部分,而不是匹配词本身:

Pattern regex1 = Pattern.compile(
    "\\b     # Match word boundary\n" +
    "from    # Match 'from'\n" +
    "\\s+    # Match whitespace\n" +
    "(.+?)   # Match one or more characters\n" +
    "\\b     # Match word boundary\n" +
    "to      # Match 'to'\n" +
    "\\s+    # Match whitespace\n" +
    "(.+)    # Match one or more characters", 
    Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS);
Pattern regex2 = Pattern.compile("\\bto\\s+(.+?)\\bfrom\\s+(.+)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS);

Matcher regexMatcher = regex1.matcher(subjectString);
if (regexMatcher.find()) {
    fromString = regexMatcher.group(1);
    destString = regexMatcher.group(2);
} else {
    Matcher regexMatcher = regex2.matcher(subjectString);
    if (regexMatcher.find()) {
        fromString = regexMatcher.group(1);
        destString = regexMatcher.group(2);
    }   
}
于 2012-04-23T06:55:35.457 回答
0

我能想到的最简单的一个是.*(from).*(to).*

于 2012-04-23T01:46:57.393 回答
0

(?<=from\s)(.*)(?<=\sto)(.*)应该管用。

于 2012-04-23T01:56:01.027 回答