任何人都可以给我一手正则表达式吗?
我正在阅读“地点”列表中进行简单的文字冒险(那些在当天如此受欢迎)。但是,我不确定如何获得输入。
所有地点都遵循以下格式:
<location_name>, [<item>]
[direction, location_name]
如:
Albus Square, Flowers, Traffic Cone
NORTH, Franklandclaw Lecture Theatre
WEST, Library of Enchanted Books
SOUTH, Furnesspuff College
Library of Enchanted Books
EAST, Albus Square
UP, Reading Room
(后续位置用空行分隔。)
我将这些存储为具有结构的位置对象:
public class Location {
private String name;
private Map<Direction, Location> links;
private List<Item> items;
}
我使用一种方法从URL中检索数据并从读取的文本中创建Location对象,但我完全阻止这样做。我认为正则表达式会有所帮助。任何人都可以借给我一个急需的手吗?
答案 0 :(得分:3)
您不希望为此使用纯文本格式:
当您有多个花卉项目时会发生什么?它们都一样吗?一个冒险家不能通过在几个地方采摘单花收集一个bouqet?
可能会有几个同名的房间(“地窖”,“街角”),即填充室增加了气氛,但没有任何游戏。但是,他们没有得到自己的描述。如何让他们分开?
如果名称包含逗号怎么办?
最后,您需要将Unicode用于外国名称或格式说明。
由于这是结构化数据,可能包含许多奇怪的情况,我建议使用XML:
<locations>
<location>
<name>Albus Square</name>
<summary>Short description for returning adventurer</summary>
<description>Long text here ... with formatting, etc.</description>
<items>
<item>Flowers</item>
<item>Traffic Cone</item>
<items>
<directions>
<north>Franklandclaw Lecture Theatre</north>
<west>Library of Enchanted Books</west>
<south>Furnesspuff College</south>
</directions>
</location>
<location>
<name>Library of Enchanted Books</name>
<directions>
<east>Albus Square</east>
<up>Reading Room</up>
</directions>
</location>
</locations>
这允许更大的灵活性,解决了许多问题,如格式化描述文本,Unicode字符等。此外,您可以使用ID(数字)而不是文本来使用多个具有相同名称的项目/位置。
答案 1 :(得分:3)
同意w / willcodejavaforfood,可以使用正则表达式,但这不是一个很大的推动。
听起来你只需要一点算法帮助(随附p-code代码)......
currloc = null
while( line from file )
if line begins w/ whitespace
(dir, loc) = split( line, ", " )
add dir, loc to currloc
else
newlocdata = split( line, ", " )
currloc = newlocdata[0]
for i = 1 to size( newlocdata ) - 1
item = newlocdata[i]
add item to currloc
答案 2 :(得分:2)
现在无法让我的头脑进入Java模式,所以这里应该有一些伪代码:
Data = MyString.split('\n\n++\s*+');
for ( i=0 ; i<Data.length ; i++ )
{
CurLocation = Data[i].split('\n\s*+');
LocationInfo = CurLocation[0].split(',\s*+');
LocationName = LocationInfo[0];
for ( n=1 ; n<LocationInfo.length ; n++ )
{
Items[n-1] = LocationInfo[n];
}
for ( n=1 ; n<CurLocation.length ; n++ )
{
DirectionInfo = LocationInfo[n].split(',\s*+');
DirectionName = DirectionInfo[0];
for ( x=1 ; x<DirectionInfo.length ; x++ )
{
DirectionLocation[x-1] = DirectionInfo[x];
}
}
}
答案 3 :(得分:0)
您可以更改数据的格式吗?这种格式很笨拙。我怀疑你正忙着重新发明方形轮......这让我觉得“只是使用XML”。
答案 4 :(得分:-1)
我认为使用XML是过度杀戮(用大炮射击麻雀),而正则表达“不足”(使用太弱的工具,用牙刷擦洗地板)。
正确的平衡听起来像是“.ini格式”或“带有部分的邮件标题”。对于python,http://docs.python.org/library/configparser.html有图书馆文档。
一个简短的例子:
[albus_square]
name: Albus Square
items: Flowers, Traffic Cone
north: lecture_theatre
west: library_enchanted_books
south: furnesspuff_college
我假设这个格式有一个Java库。正如另一张海报所指出的那样,你可能会发生名称冲突,所以我冒昧地添加了一个“名字:”字段。方括号中的名称将是唯一标识符。