我需要查找文本字符串,它是否具有嵌套循环?我可以使用正则表达式查找嵌套循环数吗?
所以我的文字示例是:
Library-Bookshelf-Book-Book-EndBookShelf-BookShelf-Book-EndBookShelf-Library
我要搜索:Whether the String belongs to the Library that has more than 1 Bookshelf in one at least has more than 1 books ?
。使用正则表达式是否可能。我感谢其他任何想法。谢谢。
因此输入是上面的示例字符串。所需的输出将是找到的第一个匹配项。我需要在第一次出现时将它们拆分。
Bookshelf-Book-Book-EndBookShelf
BookShelf-Book-EndBookShelf
但是我的正则表达式返回:
Bookshelf-Book-Book-EndBookShelf-BookShelf-Book-EndBookShelf
BookShelf-Book-EndBookShelf
测试案例2:
Library-Bookshelf-Book-author-author-location-Book-author-EndBookShelf-BookShelf-Book-author-EndBookShelf-Library
使用正则表达式,我需要确定图书馆中的书架是否有超过2本书,对于一本书,它是否有一位以上的作者。 Tescase 2应该返回一个匹配项,因为第一部分Bookshelf-Book-author-author-author-location-Book-author-EndBookShelf满足条件。
谢谢..
答案 0 :(得分:0)
这样的事情
public static void main(String[] args) {
// TODO Auto-generated method stub
String x = "Library-BookShelf-Book-author-author-location-Book-author-EndBookShelf-BookShelf-Book-author-EndBookShelf-Library";
List<String> bookShelves = fun(x, "BookShelf", "EndBookShelf");
for (String book : bookShelves)
{
List<String> authors = null;
if(book.indexOf("Book") == book.lastIndexOf("Book"))
authors = fun(book, "Book", "Book");
else
authors = fun(book, "Book", "EndBookShelf");
}
}
public static List<String> fun(String input, String startTag, String endTag){
String [] c = input.split("-");
List<Integer> shelfIndices = getIndices(c, startTag, endTag);
List<String> answer = new ArrayList<String>();
int i=0;
while (i<shelfIndices.size()-1)
{
int start = shelfIndices.get(i);
int end = shelfIndices.get(i+1);
StringBuilder res = new StringBuilder();
res.append(startTag+"-");
for (int j=start+1; j<end; j++)
{
res.append(c[j]+"-");
}
res.append(endTag);
answer.add(res.toString());
i+=2;
}
for(String r: answer)
System.out.println(r);
return answer;
}
public static List<Integer> getIndices(String [] c, String startTag, String endTag){
List<Integer> indices = new ArrayList<Integer>();
for (int i=0; i<c.length; i++)
{
if (c[i].equals(startTag) || c[i].equals(endTag))
{
indices.add(i);
}
}
return indices;
}
这将打印出来
BookShelf-Book-author-author-location-Book-author-EndBookShelf
BookShelf-Book-author-EndBookShelf
Book-author-author-location-EndBookShelf
Book-author-EndBookShelf
答案 1 :(得分:-1)
尝试使用正则表达式:Bookshelf-(?:Book-)*EndBookShelf