[英]Regex for Parsing Simple Text-Based Datafile
誰能給我一點正則表達式的幫助?
我正在閱讀一個“位置”列表,以進行簡單的文字冒險(那些在當時很流行的冒險)。 但是,我不確定如何獲取輸入。
所有位置均遵循以下格式:
<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
(后續位置由空白行分隔。)
我將這些存儲為具有以下結構的Location對象:
public class Location {
private String name;
private Map<Direction, Location> links;
private List<Item> items;
}
我使用一種方法來從URL檢索數據並從讀取的文本創建Location對象,但是我在一個完整的步驟上這樣做。 我認為正則表達式會有所幫助。 有人可以幫我一把嗎?
您不想為此使用純文本格式:
如果您擁有一個以上的花朵,會發生什么? 他們都一樣嗎? 冒險家不能在幾個位置采摘鮮花來收集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(數字)代替文本來使用多個具有相同名稱的項目/位置。
同意使用willcodejavaforfood,可以使用正則表達式,但在這里並不是很大的提升。
聽起來您只需要一點算法幫助即可(緊隨其后的p代碼)...
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
現在無法進入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];
}
}
}
您可以更改數據格式嗎? 這種格式很笨拙。 我懷疑您正在忙於重新設計方形齒輪...這對我來說是“只使用XML”。
我認為使用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庫用於這種格式。 正如另一位海報指出的那樣,您可能會遇到名稱沖突,因此我隨意添加了“名稱:”字段。 方括號中的名稱將是唯一標識符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.