1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.compatibility.common.util; 18 19 import java.util.regex.Pattern; 20 21 public class TextUtils { TextUtils()22 private TextUtils() { 23 } 24 25 /** 26 * Return the first section in {@code source} between the line matches 27 * {@code extractionStartRegex} and the line matches {@code extractionEndRegex}. 28 */ extractSection(String source, String extractionStartRegex, boolean startInclusive, String extractionEndRegex, boolean endInclusive)29 public static String extractSection(String source, 30 String extractionStartRegex, boolean startInclusive, 31 String extractionEndRegex, boolean endInclusive) { 32 33 final Pattern start = Pattern.compile(extractionStartRegex); 34 final Pattern end = Pattern.compile(extractionEndRegex); 35 36 final StringBuilder sb = new StringBuilder(); 37 final String[] lines = source.split("\\n", -1); 38 39 int i = 0; 40 for (; i < lines.length; i++) { 41 final String line = lines[i]; 42 if (start.matcher(line).matches()) { 43 if (startInclusive) { 44 sb.append(line); 45 sb.append('\n'); 46 } 47 i++; 48 break; 49 } 50 } 51 52 for (; i < lines.length; i++) { 53 final String line = lines[i]; 54 if (end.matcher(line).matches()) { 55 if (endInclusive) { 56 sb.append(line); 57 sb.append('\n'); 58 } 59 break; 60 } 61 sb.append(line); 62 sb.append('\n'); 63 } 64 return sb.toString(); 65 } 66 67 /** 68 * Creates a string consisted of {@code size} chars {@code c}. 69 */ repeat(char c, int size)70 public static String repeat(char c, int size) { 71 StringBuilder builder = new StringBuilder(size); 72 for (int i = 1; i <= size; i++) { 73 builder.append(c); 74 } 75 return builder.toString(); 76 } 77 } 78