0

起初:对不起标题,不知道更好。我对正则表达式也很陌生。

我目前正在编写一些可以分析物品/武器名称(来自游戏)的东西。

我想匹配这样的名称:

Windwalkers angry Leather Claws of Destruction

具有以下匹配组:

  1. 风行者
  2. 生气的
  3. 皮爪
  4. 破坏

项目名称有一个命名方案:

<> = required, [] = optional
[itemgroup] [adjective] < material name with spaces > [of [source]]

组、形容词和来源不包含任何空格。

我想出了这个:

(\w*) (\w*) (.+) of (.*)

它根本不处理某些部分是可选的,如果匹配组始终保持不变,那将是很好的,所以 2 将始终是形容词,可能是空白的。

谢谢你的帮助。

4

4 回答 4

2

您可以将其拆分为一行:

String[] parts = str.split("(?<!Leather|Steel|Wood(en)?|Glass|Iron|Bronze) (of )?");

您可以根据需要添加任意数量的形容词。

这使用否定的后视来断言被分割的空间前面没有形容词。可选项(of )?消耗术语之间的“of”。


这是一个测试:

String str = "Windwalkers angry Leather Claws of Destruction";
String[] parts = str.split("(?<!Leather|Steel|Wood(en)?|Glass|Iron|Bronze) (of )?");
System.out.println(Arrays.toString(parts));

输出:

[Windwalkers, angry, Leather Claws, Destruction]
于 2013-08-20T22:57:20.527 回答
1

你不能用正则表达式做你想做的事,因为没有办法判断第一个单词是项目组、形容词还是材料名称的一部分。我认为正则表达式方法是错误的方法。相反,考虑创建一个List<String>允许的项目组,另一个List<String>用于形容词,一个用于材料名称。那么如果input是输入名称:

String work = input;
for (String itemgroup : itemgroupList)
    if (work.startsWith (itemgroup.concat (" ")) {
        // itemgroup is now the item group you want
        work = work.substring (itemgroup.length()).trim();
        // remove itemgroup from the front of work, and discard leftover leading
        // spaces
    }

这将测试当前字符串是否以 itemgroup 开头。如果是这样,它会从工作字符串中删除 itemgroup,然后您可以对您的形容词和材料列表执行类似的操作。如果没有,则工作字符串不会更改,但是您可以查找形容词和材料。我唯一会使用正则表达式的是“of”部分。与尝试使用正则表达式做任何事情相比,这样做的好处是您可以轻松地从任何允许的可能性列表中添加或删除项目。(当你到达输入的末尾时要小心;我上面的代码在后面附加了一个空格,itemgroup因为我认为itemgroup后面必须跟一个空格,但材料名称并不总是这样。)

于 2013-08-20T23:45:31.280 回答
1

以下正则表达式应该为您提供您所追求的值:

  ^(\w* )?(\w* )?(\w* \w*) of (\w*)$

这里唯一重要的假设是项目名称中只有一个空格('Leather Claws') - 如果不是这种情况,那么我不相信这可以通过使用正则表达式来实现。也就是说,这种情况在任何自动解析器上都很难处理,除非你的问题没有提到固定的语法。

输入: Windwalkers angry Leather Claws of Destruction

输出:

  1. 风行者
  2. 生气的
  3. 皮爪
  4. 破坏

输入: Windwalkers Leather Claws of Destruction

输出:

  1. 风行者
  2. <空白>
  3. 皮爪
  4. 破坏

输入: Leather Claws of Destruction

输出:

  1. <空白>
  2. <空白>
  3. 皮爪
  4. 破坏

这些是我可以从您的问题中确定的唯一测试用例,但它可以正确解析它们,甚至保留相同的匹配组。

请参阅http://www.rubular.com/r/7AT4kDVf8S上的演示

于 2013-08-21T08:56:34.003 回答
0
\[([a-z A-Z]*)\]\s\[([a-z A-Z]*)\] <(.*)\>\s\[of\s\[([a-z A-Z]*)\]\] 

这是正则表达式模式。我对您所说的选项部分有点困惑,但使用 | 打电话给 ors 所以也许这可以帮助你以及我提供的网站。

() 被称为组,您可以从中解析内容。

这个网站非常适合正则表达式!

http://www.debuggex.com/

编辑:对于可选部分,只需制作不同的正则表达式模式,如果一个失败 ifelse 另一个适合另一种模式的模式。

于 2013-08-20T23:34:58.713 回答