Java Code Examples for java.util.regex.Matcher#start()

The following examples show how to use java.util.regex.Matcher#start() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DiffUtils.java    From onedev with MIT License 6 votes vote down vote up
private static List<Long> splitByWord(String line, long token) {
	int beginPos = TokenUtils.getBeginPos(token);
	int endPos = TokenUtils.getEndPos(token);
	int typeId = TokenUtils.getTypeId(token);
	String text = TokenUtils.getText(line, token);
	List<Long> tokens = new ArrayList<>();
	Matcher matcher = pattern.matcher(text);
	int lastEnd = 0;
	while (matcher.find()) {
		int start = matcher.start();
		if (start > lastEnd)
			tokens.add(TokenUtils.getToken(lastEnd+beginPos, start+beginPos, typeId));
           tokens.add(TokenUtils.getToken(matcher.start()+beginPos, matcher.end()+beginPos, typeId));
           lastEnd = matcher.end();
       }
	if (lastEnd < text.length())
		tokens.add(TokenUtils.getToken(lastEnd+beginPos, endPos, typeId));
	return tokens;
}
 
Example 2
Source File: EntityUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the filter predicate for a given filter string
 *
 * <br/><b>Example:</b>
 * <pre>
 *   >> "country != us"
 *   << {"country", "!=", "us"}
 * </pre>
 *
 * @param filterString raw (decoded) filter string
 * @return filter predicate
 */
public static FilterPredicate extractFilterPredicate(String filterString) {
  Matcher m = PATTERN_FILTER_OPERATOR.matcher(filterString);
  if (!m.find()) {
    throw new IllegalArgumentException(
        String.format("Could not find filter predicate operator. Expected regex '%s'", PATTERN_FILTER_OPERATOR.pattern()));
  }

  int keyStart = 0;
  int keyEnd = m.start();
  String key = filterString.substring(keyStart, keyEnd);

  int opStart = m.start();
  int opEnd = m.end();
  String operator = filterString.substring(opStart, opEnd);

  int valueStart = m.end();
  int valueEnd = filterString.length();
  String value = filterString.substring(valueStart, valueEnd);

  return new FilterPredicate(key, operator, value);
}
 
Example 3
Source File: SchemaLocation.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
public SchemaLocation(DOMAttr attr) {
	this.attr = attr;
	this.schemaLocationValuePairs = new HashMap<>();
	String value = attr.getValue();
	Matcher locPairMatcher = SCHEMA_LOCATION_PAIR_PATTERN.matcher(value);
	while (locPairMatcher.find()) {
		String namespaceURI = locPairMatcher.group(1);
		String locationHint = locPairMatcher.group(2);
		if (namespaceURI == null || locationHint == null) {
			break;
		}
		DOMNode valNode = attr.getNodeAttrValue();
		// http://example.org/schema/root |root.xsd http://example.org/schema/bison bison.xsd
		int start = valNode.getStart() + locPairMatcher.start(2) + 1;
		// http://example.org/schema/root root.xsd| http://example.org/schema/bison bison.xsd
		int end = valNode.getStart() + locPairMatcher.end(2) + 1;
		schemaLocationValuePairs.put(namespaceURI,
				new SchemaLocationHint(start, end, locationHint, this));
	}
}
 
Example 4
Source File: CssFileModel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Collection<Entry> getImportsFromURI(Node resourceIdentifier) {
    Collection<Entry> files = new ArrayList<>();
    //@import url("another.css");
    Node token = NodeUtil.getChildTokenNode(resourceIdentifier, CssTokenId.URI);
    if (token != null) {
        Matcher m = Css3Utils.URI_PATTERN.matcher(token.image());
        if (m.matches()) {
            int groupIndex = 1;
            String content = m.group(groupIndex);
            boolean quoted = WebUtils.isValueQuoted(content);
            int from = token.from() + m.start(groupIndex) + (quoted ? 1 : 0);
            int to = token.from() + m.end(groupIndex) - (quoted ? 1 : 0);
            files.add(createEntry(WebUtils.unquotedValue(content),
                    new OffsetRange(from, to),
                    false));
        }
    }
    return files;
}
 
Example 5
Source File: HivePushDownConverter.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
public static String extractReplace(String originString) {
    Matcher extractMatcher = EXTRACT_PATTERN.matcher(originString);
    String replacedString = originString;
    Map<Integer, Integer> parenthesesPairs = null;

    while (extractMatcher.find()) {
        if (parenthesesPairs == null) {
            parenthesesPairs = findParenthesesPairs(originString);
        }

        String functionStr = extractMatcher.group(2);
        int startIdx = extractMatcher.end(3);
        int endIdx = parenthesesPairs.get(extractMatcher.start(1));
        String extractInner = originString.substring(startIdx, endIdx);
        int originStart = extractMatcher.start(0);
        int originEnd = endIdx + 1;

        replacedString = replaceString(replacedString, originString.substring(originStart, originEnd),
                functionStr + "(" + extractInner + ")");
    }

    return replacedString;
}
 
Example 6
Source File: KernelComm.java    From TelegramApi with MIT License 6 votes vote down vote up
@NotNull
private String readBoldEntities(@NotNull TLVector<TLAbsMessageEntity> entities, @NotNull String message) {
    final StringBuilder finalMessage = new StringBuilder();
    int lastAddedIndex = 0;
    final Matcher matcher = boldMarkdownRegex.matcher(message);

    while (matcher.find()) {
        final int startIndex = matcher.start();
        final int lastIndex = matcher.end();
        finalMessage.append(message.substring(lastAddedIndex, startIndex));
        final int initMarkdown = finalMessage.length();
        finalMessage.append(message.substring(startIndex + 1, lastIndex-1));
        lastAddedIndex = lastIndex;
        final TLMessageEntityBold boldEntity = new TLMessageEntityBold();
        boldEntity.setOffset(initMarkdown);
        boldEntity.setLength(lastIndex - startIndex - 2);
        entities.add(boldEntity);
    }

    if (lastAddedIndex != message.length()) {
        finalMessage.append(message.substring(lastAddedIndex));
    }

    return finalMessage.toString();
}
 
Example 7
Source File: MessageTreeNode.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static MessageTreeNode createInfoMessage(XDebuggerTree tree, @Nonnull String message, @Nullable HyperlinkListener hyperlinkListener) {
  Matcher matcher = MessageTreeNodeWithLinks.HREF_PATTERN.matcher(message);
  if (hyperlinkListener == null || !matcher.find()) {
    return new MessageTreeNode(tree, null, message, SimpleTextAttributes.REGULAR_ATTRIBUTES, XDebuggerUIConstants.INFORMATION_MESSAGE_ICON);
  }

  List<Object> objects = new ArrayList<Object>();
  int prev = 0;
  do {
    if (matcher.start() != prev) {
      objects.add(message.substring(prev, matcher.start()));
    }
    objects.add(new HyperlinkListenerDelegator(matcher.group(2), matcher.group(1), hyperlinkListener));
    prev = matcher.end();
  }
  while (matcher.find());

  if (prev < message.length()) {
    objects.add(message.substring(prev));
  }
  return new MessageTreeNodeWithLinks(tree, objects);
}
 
Example 8
Source File: MVCValid.java    From japi with MIT License 5 votes vote down vote up
private List<IRequest> getRequestInfos(String parameterStrExcTypeAndName, String typeStr, String nameStr, List<String> docs) {
    Matcher singleAnnoMatcher = JapiPattern.getPattern("@[a-zA-Z0-9_]*").matcher(parameterStrExcTypeAndName);
    List<String> annos = new ArrayList<>();
    int preIndex = -1, nextIndex = -1;
    while (singleAnnoMatcher.find()) {
        nextIndex = singleAnnoMatcher.start();
        if (-1 != preIndex) {
            annos.add(parameterStrExcTypeAndName.substring(preIndex, nextIndex).trim());
            preIndex = nextIndex;
        } else {
            preIndex = 0;
        }
    }
    if (nextIndex != -1) {
        annos.add(parameterStrExcTypeAndName.substring(nextIndex).trim());
    }
    List<IRequest> requestFields = new ArrayList<>();
    for (String annoStr : annos) {
        if (isValid(annoStr)) {//全部使用默认值
            IMVC imvc = getValid(annoStr.substring(1));
            if (null != imvc) {
                IRequest requestField = imvc.getRequestField(parameterStrExcTypeAndName, typeStr, nameStr, docs,new File(javaFilePath));
                if(null!=requestField){
                    requestFields.add(requestField);
                }
            }
        } else {
            LOGGER.warn(annoStr + " 不在MVCValid识别范围内.");
        }
    }
    return requestFields;
}
 
Example 9
Source File: CfgPropsCompletionQuery.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
@Override
protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) {
    logger.finer("Starting completion");
    final StyledDocument styDoc = (StyledDocument) document;
    Element lineElement = styDoc.getParagraphElement(caretOffset);
    int lineStartOffset = lineElement.getStartOffset();
    try {
        String lineToCaret = styDoc.getText(lineStartOffset, caretOffset - lineStartOffset);
        if (!lineToCaret.contains("#")) {
            String[] parts = lineToCaret.split("=");
            //property name extraction from part before =
            Matcher matcher = PATTERN_PROP_NAME.matcher(parts[0]);
            String propPrefix = null;
            int propPrefixOffset = 0;
            while (matcher.find()) {
                propPrefix = matcher.group();
                propPrefixOffset = matcher.start();
            }
            // check which kind of completion
            final int equalSignOffset = lineToCaret.indexOf('=');
            if (parts.length > 1) {
                //value completion
                String valPrefix = parts[1].trim();
                completePropValue(completionResultSet, propPrefix, valPrefix, lineStartOffset
                        + lineToCaret.indexOf(valPrefix, equalSignOffset), caretOffset);
            } else if (equalSignOffset >= 0) {
                //value completion with empty filter
                completePropValue(completionResultSet, propPrefix, "", lineStartOffset + equalSignOffset + 1, caretOffset);
            } else {
                // property completion
                completePropName(completionResultSet, propPrefix, lineStartOffset + propPrefixOffset, caretOffset);
            }
        }
    } catch (BadLocationException ex) {
        Exceptions.printStackTrace(ex);
    }
    completionResultSet.finish();
}
 
Example 10
Source File: StringUtil.java    From SoloPi with Apache License 2.0 5 votes vote down vote up
/**
 * 正则替换
 * @param origin 原始字段
 * @param pattern 正则模板
 * @param replace 替换方法
 * @return
 */
public static String patternReplace(CharSequence origin, Pattern pattern, PatternReplace replace) {
    if (origin == null || replace == null || pattern == null) {
        return null;
    }

    // 正则匹配下
    Matcher matcher = pattern.matcher(origin);
    StringBuilder sb = new StringBuilder();

    int currentIdx = 0;
    // 替换所有匹配到的字段
    while (matcher.find()) {
        // 添加之前的字段
        int start = matcher.start();
        sb.append(origin.subSequence(currentIdx, start));

        // 替换match字段
        String content = replace.replacePattern(matcher.group());
        sb.append(content);

        // 重置偏移量
        currentIdx = start + matcher.group().length();
    }

    // 如果还有其他字段
    if (currentIdx < origin.length()) {
        sb.append(origin.subSequence(currentIdx, origin.length()));
    }

    return sb.toString();
}
 
Example 11
Source File: HighLightKeyWordUtil.java    From styT with Apache License 2.0 5 votes vote down vote up
/**
 * @param color   关键字颜色
 * @param text    文本
 * @param keyword 关键字
 * @return
 */
public static SpannableString getHighLightKeyWord(int color, String text, String keyword) {
    SpannableString s = new SpannableString(text);
    Pattern p = Pattern.compile(keyword);
    Matcher m = p.matcher(s);
    while (m.find()) {
        int start = m.start();
        int end = m.end();
        s.setSpan(new ForegroundColorSpan(color), start, end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return s;
}
 
Example 12
Source File: Formatter.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Finds format specifiers in the format string.
 */
private List<FormatString> parse(String s) {
    ArrayList<FormatString> al = new ArrayList<>();
    Matcher m = fsPattern.matcher(s);
    for (int i = 0, len = s.length(); i < len; ) {
        if (m.find(i)) {
            // Anything between the start of the string and the beginning
            // of the format specifier is either fixed text or contains
            // an invalid format string.
            if (m.start() != i) {
                // Make sure we didn't miss any invalid format specifiers
                checkText(s, i, m.start());
                // Assume previous characters were fixed text
                al.add(new FixedString(s, i, m.start()));
            }

            al.add(new FormatSpecifier(s, m));
            i = m.end();
        } else {
            // No more valid format specifiers.  Check for possible invalid
            // format specifiers.
            checkText(s, i, len);
            // The rest of the string is fixed text
            al.add(new FixedString(s, i, s.length()));
            break;
        }
    }
    return al;
}
 
Example 13
Source File: GenerateSamples.java    From stringbench with Apache License 2.0 5 votes vote down vote up
private static String[] splitPattern(String line) {
	Matcher m = PATTERN_LINE.matcher(line);
	if (m.find()) {
		int pos = m.start();
		return new String[] { line.substring(0, pos), m.group(1) };
	} else {
		return new String[] { line, "0" };
	}
}
 
Example 14
Source File: ENDayOfWeekDateFormatParser.java    From chrono-java with MIT License 5 votes vote down vote up
@Override
protected ParsedResult extract(String text, Date refDate, Matcher matcher, ChronoOption option) {

    Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
    calendar.setTime(refDate);

    ParsedResult result = new ParsedResult(this, matcher.start(), matcher.group());

    int dayOfWeek = EnglishConstants.valueForDayOfWeek(matcher.group(2));
    int today = calendar.get(Calendar.DAY_OF_WEEK);

    if (matcher.group(1) == null || matcher.group(1).toLowerCase().equals("this")) {

        if (Math.abs(dayOfWeek - 7 - today) < Math.abs(dayOfWeek - today)) {
            calendar.add(Calendar.WEEK_OF_YEAR, -1);
        } else if (Math.abs(dayOfWeek + 7 - today) < Math.abs(dayOfWeek - today)) {
            calendar.add(Calendar.WEEK_OF_YEAR, 1);
        }

    } else {

        if (matcher.group(1).toLowerCase().equals("last")) {
            calendar.add(Calendar.WEEK_OF_YEAR, -1);
        } else if (matcher.group(1).toLowerCase().equals("next")) {
            calendar.add(Calendar.WEEK_OF_YEAR, 1);
        }
    }

    calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);

    result.start = new ParsedDateComponent();
    result.start.imply(Components.Year, calendar.get(Calendar.YEAR));
    result.start.imply(Components.Month, calendar.get(Calendar.MONTH) + 1);
    result.start.imply(Components.DayOfMonth, calendar.get(Calendar.DAY_OF_MONTH));
    result.start.assign(Components.DayOfWeek, dayOfWeek);

    return result;
}
 
Example 15
Source File: Formatter.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Finds format specifiers in the format string.
 */
private FormatString[] parse(String s) {
    ArrayList<FormatString> al = new ArrayList<>();
    Matcher m = fsPattern.matcher(s);
    for (int i = 0, len = s.length(); i < len; ) {
        if (m.find(i)) {
            // Anything between the start of the string and the beginning
            // of the format specifier is either fixed text or contains
            // an invalid format string.
            if (m.start() != i) {
                // Make sure we didn't miss any invalid format specifiers
                checkText(s, i, m.start());
                // Assume previous characters were fixed text
                al.add(new FixedString(s.substring(i, m.start())));
            }

            al.add(new FormatSpecifier(m));
            i = m.end();
        } else {
            // No more valid format specifiers.  Check for possible invalid
            // format specifiers.
            checkText(s, i, len);
            // The rest of the string is fixed text
            al.add(new FixedString(s.substring(i)));
            break;
        }
    }
    return al.toArray(new FormatString[al.size()]);
}
 
Example 16
Source File: StringUtil.java    From sagacity-sqltoy with Apache License 2.0 5 votes vote down vote up
public static int matchIndex(String source, Pattern p) {
	Matcher m = p.matcher(source);
	if (m.find()) {
		return m.start();
	}
	return -1;
}
 
Example 17
Source File: AppendableBuilder.java    From cucumber-performance with MIT License 4 votes vote down vote up
private String parsePostFix(String argument) {
	String[] a = argument.split("\\.");
	List<String> args = new ArrayList<String>();
	// if there was an extension
	if (a.length > 1) {
		Matcher ms = ARGUMENT_POSTFIX_SEPARATOR_PATTERN.matcher(a[0]);
		// if separator
		int last = 0;
		while (ms.find()) {
			if (ms.start() > 0) {
				args.add(a[0].substring(last, ms.start()));
				last = ms.start() + 1;
			}
		}
		if (last > 0 && last != a[0].length()) {
			args.add(a[0].substring(last, a[0].length()));
		}

		if (args.size() == 0) {
			// no separator
			args.add(a[0]);
		}
	}

	for (String larg : args) {
		Matcher m = ARGUMENT_POSTFIX_PART_PATTERN.matcher(larg);
		while (m.find()) {
			String value = larg.substring(m.start(), m.end());
			try {
				Integer.parseInt(value);
				count = count+1;
				argument = argument.replace("#" + value,
						String.format("%0" + (value.length())+ "d", count));
			} catch (NumberFormatException n) {
				if (!value.isEmpty()) {
					argument = argument.replace("@" + value, parsePostFixDate(value));
				}
			}
		}
	}
	return argument;
}
 
Example 18
Source File: TagParser.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static Result parseTags(TokenSequence<JavaTokenId> ts) {
    while (ts.moveNext()) {
        if (ts.token().id() == JavaTokenId.BLOCK_COMMENT || ts.token().id() == JavaTokenId.JAVADOC_COMMENT) {
            String text = ts.token().text().toString();

            if (text.contains("@test")) {
                List<Tag> tags = new ArrayList<>();
                int start = -1;
                int end = -1;
                int tagStart = -1;
                int tagEnd = -1;

                text = text.substring(0, text.length() - 2);

                String tagName = null;
                StringBuilder tagText = new StringBuilder();
                int prefix = ts.token().id() == JavaTokenId.BLOCK_COMMENT ? 2 : 3;
                String[] lines = text.substring(prefix).split("\n");
                int pos = ts.offset() + prefix;

                for (String line : lines) {
                    if (line.replaceAll("[*\\s]+", "").isEmpty()) {
                        pos += line.length() + 1;
                        continue;
                    }
                    Matcher m = TAG_PATTERN.matcher(line);
                    if (m.find()) {
                        if (tagName != null) {
                            tags.add(new Tag(start, pos, tagStart, tagEnd, tagName, tagText.toString()));
                            tagText.delete(0, tagText.length());
                        }

                        tagName = m.group(1);

                        start = pos;
                        tagStart = pos + m.start();
                        tagEnd = pos + m.end(1);
                        tagText.append(line.substring(m.end(1)));
                    } else if (tagName != null) {
                        int asterisk = line.indexOf('*');
                        tagText.append(line.substring(asterisk + 1));
                    }

                    pos += line.length() + 1;

                    if (tagName != null) {
                        end = pos;
                    }
                }

                if (tagName != null) {
                    tags.add(new Tag(start, end, tagStart, tagEnd, tagName, tagText.toString()));
                }

                Map<String, List<Tag>> result = new HashMap<>();

                for (Tag tag : tags) {
                    List<Tag> innerTags = result.get(tag.getName());

                    if (innerTags == null) {
                        result.put(tag.getName(), innerTags = new ArrayList<>());
                    }

                    innerTags.add(tag);
                }

                return new Result(tags, result);
            }
        }
    }

    return new Result(Collections.<Tag>emptyList(), Collections.<String, List<Tag>>emptyMap());
}
 
Example 19
Source File: CompletionContextTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void prepareData(String tokenName, String fname) throws Exception  {
    File dataDir = getDataDir();
    File f = new File(dataDir, CompletionContextTest.class.getPackage().getName().replaceAll("\\.", "/") + 
            "/" + fname);
    InputStream stream = new FileInputStream(f);
    InputStreamReader rd = new InputStreamReader(stream, "UTF-8");
    
    StringBuffer sb = new StringBuffer();
    CharBuffer cb = CharBuffer.allocate(10000);
    
    while (rd.read(cb) != -1) {
        cb.flip();
        sb.append(cb.toString());
        cb.rewind();
    }
    rd.close();
    
    String text = sb.toString();
    
    // strip all occurrences of markers:
    String pristine = text.replaceAll(MARKER, "");
    
    Pattern p = Pattern.compile(MARKER);
    Matcher m = p.matcher(text);
    TestSuite ts = new TestSuite(CompletionContextTest.class.getName());
    
    while (m.find()) {
        String val = m.group(1);
        String name = m.group(2);
        
        if (!name.equals(tokenName)) {
            continue;
        }
        
        int offset = m.start();
        String cleanBefore = text.substring(0, offset).replaceAll(MARKER, "");
        
        this.text = pristine;
        this.state = val;
        this.stateVal = CompletionContext.Type.valueOf(val);
        this.offset = cleanBefore.length();
        return;
    }
    throw new IllegalArgumentException("Token " + tokenName + " not found in the template");
}
 
Example 20
Source File: Sample18TestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
@Test(groups = {"wso2.esb"},
        description = "Transforming a Message Using ForEachMediator")
public void testTransformWithForEachMediator() throws Exception {

    LogViewerClient logViewer =
            new LogViewerClient(contextUrls.getBackEndUrl(), getSessionCookie());
    logViewer.clearLogs();

    String request =
            "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:m0=\"http://services.samples\" xmlns:xsd=\"http://services.samples/xsd\">\n" +
                    "    <soap:Header/>\n" +
                    "    <soap:Body>\n" +
                    "        <m0:getQuote>\n" +
                    "            <m0:request><m0:symbol>IBM</m0:symbol></m0:request>\n" +
                    "            <m0:request><m0:symbol>WSO2</m0:symbol></m0:request>\n" +
                    "            <m0:request><m0:symbol>MSFT</m0:symbol></m0:request>\n" +
                    "        </m0:getQuote>\n" +
                    "    </soap:Body>\n" +
                    "</soap:Envelope>\n";
    sendRequest(getMainSequenceURL(), request);

    LogEvent[] getLogsInfo = logViewer.getAllRemoteSystemLogs();
    for (LogEvent event : getLogsInfo) {

        if (event.getMessage().contains("<m0:getQuote>")) {
            assertTrue(true, "Payload not found");

            String payload = event.getMessage();
            String search = "<m0:getQuote>(.*)</m0:getQuote>";
            Pattern pattern = Pattern.compile(search, Pattern.DOTALL);
            Matcher matcher = pattern.matcher(payload);
            boolean matchFound = matcher.find();

            assertTrue(matchFound, "getQuote element not found");
            if (matchFound) {
                int start = matcher.start();
                int end = matcher.end();
                String quote = payload.substring(start, end);

                assertTrue(quote.contains(
                                "<m0:checkPriceRequest><m0:code>IBM</m0:code></m0:checkPriceRequest>"),
                        "IBM Element not found");
                assertTrue(quote.contains(
                                "<m0:checkPriceRequest><m0:code>WSO2</m0:code></m0:checkPriceRequest>"),
                        "WSO2 Element not found");
                assertTrue(quote.contains(
                                "<m0:checkPriceRequest><m0:code>MSFT</m0:code></m0:checkPriceRequest>"),
                        "MSTF Element not found");

            }
        }
    }
}