1

I have following text:

my-widget{
  color: #{mycolors.getColors(1)}
}
...
my-tridget{
  color: #{mycolors.getColors(2)}
  ...
}
...

I want to split the text in pairs, where the delimiter is #{mycolors.getColors()} and the text between previous delimeter and current delimiter will be saved. E.g. for such pairs:

Pair 1: text: my-widget{ color: number: 1

Pair 2: text: } ... my-tridget{ color: number: 2

What I am used so far,

 Pattern p = Pattern.compile("(.*)#\\{mycolors.getColor\\(([0-9])\\)\\}", Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
    Matcher m = p.matcher(data);

 while (m.find){
     String number = m.group(2).toLowerCase().trim();
     String text = m.group(1);          
 }

But number and text will be to:

text: color: number: 1

text: color: number: 2

So the text doesn't go over several lines. How can I achieve this ? (The Pattern.DOTALL in addtion to Pattern.MULTILINE didn't help me)

4

1 回答 1

1

你犯的一些错误:

  1. 要跨多行匹配文本,您需要使用Pattern.DOTALL而不是Pattern.MULTILINE
  2. 而不是.*让它不贪婪.*?
  3. 您的文本有字符串getColors,但您getColor的正则表达式中有

以下正则表达式模式应该适合您:

Pattern p = Pattern.compile("(.*?)#\\{mycolors.getColors\\((\\d+)\\)\\}", 
                            Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
于 2013-09-16T12:41:06.163 回答