下面列出了java.util.regex.Matcher#end ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* If a _ is not a word break character, see if the BreakIterator stopped on one
*
* @param doc
* @param pos
* @return new offset if word moves past any _'s, else pos
*/
int checkUnder(IDocument doc, int pos) {
int result = pos;
try {
if (!isUnder()) {
char c = doc.getChar(pos);
if (!isDot() || c != '.') {
IRegion lineInfo = doc.getLineInformationOfOffset(pos);
int p = pos;
// if we're at or just moved over an _
if (c == '_' || (--p >= lineInfo.getOffset() && doc.getChar(p) == '_')) {
int end = (lineInfo.getOffset() + lineInfo.getLength());
if (end > p) {
Matcher matcher = getUnderMatcher();
matcher.reset(doc.get(p, end - p));
if (matcher.matches()) {
result = p + matcher.end(1);
}
}
}
}
}
} catch (BadLocationException e) {
}
return result;
}
public static void setHighlight(JTextComponent jtc, String pattern) {
jtc.getHighlighter().removeAllHighlights();
try {
Highlighter highlighter = jtc.getHighlighter();
Document doc = jtc.getDocument();
String text = doc.getText(0, doc.getLength());
Matcher matcher = Pattern.compile(pattern).matcher(text);
int pos = 0;
while (matcher.find(pos) && !matcher.group().isEmpty()) {
pos = matcher.end();
highlighter.addHighlight(matcher.start(), pos, HIGHLIGHT);
}
// int pos = text.indexOf(pattern);
// while (pos >= 0) {
// int np = pos + pattern.length();
// jtc.getHighlighter().addHighlight(pos, np, HIGHLIGHT);
// pos = text.indexOf(pattern, np);
// }
} catch (BadLocationException | PatternSyntaxException ex) {
UIManager.getLookAndFeel().provideErrorFeedback(jtc);
}
}
@NotNull
private String readItalicEntities(@NotNull TLVector<TLAbsMessageEntity> entities, @NotNull String message) {
final StringBuilder finalMessage = new StringBuilder();
int lastAddedIndex = 0;
final Matcher matcher = italicMarkdownRegex.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 TLMessageEntityItalic italicEntity = new TLMessageEntityItalic();
italicEntity.setOffset(initMarkdown);
italicEntity.setLength(lastIndex - startIndex - 2);
entities.add(italicEntity);
}
if (lastAddedIndex != message.length()) {
finalMessage.append(message.substring(lastAddedIndex));
}
return finalMessage.toString();
}
/**
* 在字符串转化不同形式的emoji
*
* @param input
* @param pattern
* @param func
* @return
*/
private String replaceWithFunction(String input, Pattern pattern, Function<String, String> func) {
StringBuilder builder = new StringBuilder();
Matcher matcher = pattern.matcher(input);
int lastEnd = 0;
// find返回false则不分割
while (matcher.find()) {
// 分割并保留文本而不是emoji码
String lastText = input.substring(lastEnd, matcher.start());
// String lastText = matcher.group();
builder.append(lastText);
// 分割并保留emoji码,再讲不同形式的emoji转化成Unicode
builder.append(func.apply(matcher.group()));
lastEnd = matcher.end();
}
builder.append(input.substring(lastEnd));
return builder.toString();
}
private String stripLimit(String str)
{
if(str==null)return "";
String s = str.trim();
Matcher mt = pt.matcher(s);
if(!mt.find())
return s;
if(mt.end()==s.length())
{
s = s.substring(0, mt.start());
if(s!=null)s=s.trim();
return s;
}
mt = pt2.matcher(s);
if(!mt.find())
return s;
if(mt.end()==s.length())
{
s = s.substring(0, mt.start());
if(s!=null)s=s.trim();
return s;
}
return s;//don't care middle one
}
@Override
protected void replaceText(CharSequence text){
String beforeCursor = getText().toString().substring(0, getSelectionStart());
String afterCursor = getText().toString().substring(getSelectionStart());
Pattern pattern = Pattern.compile("#\\S*");
Matcher matcher = pattern.matcher(beforeCursor);
StringBuffer sb = new StringBuffer();
int matcherStart = 0;
while (matcher.find()) {
int curPos = getSelectionStart();
if(curPos > matcher.start() &&
curPos <= matcher.end()){
matcherStart = matcher.start();
matcher.appendReplacement(sb, text.toString()+" ");
}
}
matcher.appendTail(sb);
setText(sb.toString()+afterCursor);
setSelection(matcherStart + text.length()+1);
}
public static String getSuffix(RedisRequest request) {
if ( request.getNumArgs() <= 1) {
return null;
}
String key = new String( request.getArgs()[1] );
Matcher m = pattern.matcher(key);
if ( m.find() ) {
int beginIndex = m.start();
int endIndex = m.end();
String suffix = key.substring(beginIndex, endIndex);
String prefix = key.substring(0, beginIndex);
// 清除后缀, 使用前缀
request.getArgs()[1] = prefix.getBytes();
return suffix;
}
return null;
}
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;
}
public Range getWordRangeAt(int textOffset, Pattern wordDefinition) {
try {
Position pos = positionAt(textOffset);
ILineTracker lineTracker = getLineTracker();
Line line = lineTracker.getLineInformation(pos.getLine());
String text = super.getText();
String lineText = text.substring(line.offset, textOffset);
int position = lineText.length();
Matcher m = wordDefinition.matcher(lineText);
int currentPosition = 0;
while (currentPosition != position) {
if (m.find()) {
currentPosition = m.end();
if (currentPosition == position) {
return new Range(new Position(pos.getLine(), m.start()), pos);
}
} else {
currentPosition++;
}
m.region(currentPosition, position);
}
return new Range(pos, pos);
} catch (BadLocationException e) {
return null;
}
}
private static Collection<String> parse(final String value) {
if ("*".equals(value.trim())) {
return Collections.singleton("*");
} else {
Set<String> result = new HashSet<>();
String separator = "";
int start = 0;
Matcher matcher = ETAG.matcher(value.trim());
while (matcher.find() && matcher.start() == start) {
start = matcher.end();
if (matcher.group(1) != null) {
separator = matcher.group(1);
} else if (separator != null) {
result.add(matcher.group(2));
separator = null;
} else {
return Collections.<String> emptySet();
}
}
return matcher.hitEnd() ? result : Collections.<String> emptySet();
}
}
/**
* Parse a static body instance into a composable instance. This is an
* expensive operation and should not be used lightly.
* <p/>
* The current implementation does not obtain the payload XML by means of
* a proper XML parser. It uses some string pattern searching to find the
* first @{code body} element and the last element's closing tag. It is
* assumed that the static body's XML is well formed, etc.. This
* implementation may change in the future.
*
* @param body static body instance to convert
* @return composable body instance
* @throws BOSHException
*/
static ComposableBody fromStaticBody(final StaticBody body)
throws BOSHException {
String raw = body.toXML();
Matcher matcher = BOSH_START.matcher(raw);
if (!matcher.find()) {
throw(new BOSHException(
"Could not locate 'body' element in XML. The raw XML did"
+ " not match the pattern: " + BOSH_START));
}
String payload;
if (">".equals(matcher.group(1))) {
int first = matcher.end();
int last = raw.lastIndexOf("</");
if (last < first) {
last = first;
}
payload = raw.substring(first, last);
} else {
payload = "";
}
return new ComposableBody(body.getAttributes(), payload);
}
private void patternCSSExtract(HTMLMetaData data, Pattern pattern, String content) {
Matcher m = pattern.matcher(content);
int idx = 0;
int contentLen = content.length();
if (contentLen > 100000)
// extract URLs only from the first 100 kB
contentLen = 100000;
while((idx < contentLen) && m.find()) {
idx = m.end();
String url = m.group(1);
url = cssUrlTrimPattern.matcher(url).replaceAll("");
if (!url.isEmpty()) {
data.addHref("path","STYLE/#text","href", url);
}
}
}
/**
* Override this method to customize how versions are normalized in search.
*/
protected String getNormalizedVersion(final FluentComponent component) {
String version = component.version();
if (isBlank(version)) {
return "";
}
// Prepend any numbers in the version with 0s to make each number 9 digits
Matcher digitsMatcher = DIGITS_PATTERN.matcher(version);
StringBuilder paddedVersion = new StringBuilder();
int position = 0;
while (digitsMatcher.find()) {
paddedVersion.append(version, position, digitsMatcher.start());
position = digitsMatcher.end();
try {
paddedVersion.append(String.format("%09d", parseLong(digitsMatcher.group())));
}
catch (NumberFormatException e) {
log.debug("Unable to parse number as long '{}'", digitsMatcher.group());
paddedVersion.append(digitsMatcher.group());
}
}
return paddedVersion.toString();
}
@Override
public boolean em(Line line) {
line = line.get();
SpannableStringBuilder builder = (SpannableStringBuilder) line.getStyle();
Matcher matcher = obtain(Tag.EM, builder);
while (matcher.find()) {
int start = matcher.start(1);
int end = matcher.end(1);
if (checkInCode(builder, start, end)) {
continue;
}
SpannableStringBuilder sb = (SpannableStringBuilder) builder.subSequence(matcher.start(3), matcher.end(3));
builder.delete(matcher.start(1), matcher.end(1));
builder.insert(matcher.start(1), styleBuilder.em(sb));
em(line);
return true;
}
return false;
}
static boolean extractReferencesNaively(JCas jCas) {
// match potential sections
List<Section> sections = newArrayList();
Matcher m = REFERENCES.matcher(jCas.getDocumentText());
while (m.find()) {
Section section = new Section(jCas, m.start(), m.end());
section.setSectionType(BlueUima.SECTION_TYPE_REFERENCES);
sections.add(section);
}
if (sections.size() == 1) {
sections.get(0).addToIndexes();
return true;
}
return false;
}
@Test(groups = {"wso2.esb"}, description = "Transforming a Message Using a Nested ForEach Construct")
public void testNestedForEach() throws Exception {
carbonLogReader.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\">"
+ "<soap:Header/><soap:Body><m0:getQuote><m0:request><m0:symbol>IBM</m0:symbol></m0:request>"
+ "<m0:request><m0:symbol>WSO2</m0:symbol></m0:request><m0:request><m0:symbol>MSFT</m0:symbol></m0:request>"
+ "</m0:getQuote></soap:Body></soap:Envelope>";
simpleHttpClient = new SimpleHttpClient();
simpleHttpClient.doPost(getProxyServiceURLHttp("foreachNestedTestProxy"),
headers, request, "application/xml;charset=UTF-8");
if (carbonLogReader.checkForLog("foreach = after", DEFAULT_TIMEOUT)) {
String logs = carbonLogReader.getLogs();
String search = "<m0:getQuote>(.*)</m0:getQuote>";
Pattern pattern = Pattern.compile(search, Pattern.DOTALL);
Matcher matcher = pattern.matcher(logs);
boolean matchFound = matcher.find();
assertTrue(matchFound, "getQuote element not found");
int start = matcher.start();
int end = matcher.end();
String quote = logs.substring(start, end);
assertTrue(quote.contains(
"<m0:checkPriceRequest><m0:symbol>IBM-1</m0:symbol><m0:symbol>IBM-2</m0:symbol></m0:checkPriceRequest>"),
"IBM Element not found");
assertTrue(quote.contains(
"<m0:checkPriceRequest><m0:symbol>WSO2-1</m0:symbol><m0:symbol>WSO2-2</m0:symbol></m0:checkPriceRequest>"),
"WSO2 Element not found");
assertTrue(quote.contains(
"<m0:checkPriceRequest><m0:symbol>MSFT-1</m0:symbol><m0:symbol>MSFT-2</m0:symbol></m0:checkPriceRequest>"),
"MSFT Element not found");
}
}
public static List<String> getURLs(String originalString){
List<String> urlsSet=new ArrayList<String>();
Matcher matcher = urlPattern.matcher(originalString);
while (matcher.find()) {
int matchStart = matcher.start(1);
int matchEnd = matcher.end();
String tmpUrl=originalString.substring(matchStart,matchEnd);
urlsSet.add(tmpUrl);
// now you have the offsets of a URL match
originalString=originalString.replace(tmpUrl,"");
matcher = urlPattern.matcher(originalString);
}
return urlsSet;
}
/**
* <p>Splits the given input sequence around matches of this pattern.<p/>
* <p/>
* <p> The array returned by this method contains each substring of the input sequence
* that is terminated by another subsequence that matches this pattern or is terminated by
* the end of the input sequence.
* The substrings in the array are in the order in which they occur in the input.
* If this pattern does not match any subsequence of the input then the resulting array
* has just one element, namely the input sequence in string form.<p/>
* <p/>
* <pre>
* splitPreserveAllTokens("boo:and:foo", ":") = { "boo", ":", "and", ":", "foo"}
* splitPreserveAllTokens("boo:and:foo", "o") = { "b", "o", "o", ":and:f", "o", "o"}
* </pre>
*
* @param input The character sequence to be split
* @return The array of strings computed by splitting the input around matches of this pattern
*/
public static String[] splitPreserveAllTokens ( String input , String regex ) {
int index = 0;
Pattern p = Pattern.compile( regex );
ArrayList< String > result = new ArrayList< String >();
Matcher m = p.matcher( input );
// Add segments before each match found
int lastBeforeIdx = 0;
while ( m.find() ) {
if ( StringUtils.isNotEmpty( m.group() ) ) {
String match = input.subSequence( index , m.start() ).toString();
if ( StringUtils.isNotEmpty( match ) ) {
result.add( match );
}
result.add( input.subSequence( m.start() , m.end() ).toString() );
index = m.end();
}
}
// If no match was found, return this
if ( index == 0 ) {
return new String[]{ input };
}
final String remaining = input.subSequence( index , input.length() ).toString();
if ( StringUtils.isNotEmpty( remaining ) ) {
result.add( remaining );
}
// Construct result
return result.toArray( new String[result.size()] );
}
public AntPathStringMatcher(String pattern, boolean caseSensitive) {
StringBuilder patternBuilder = new StringBuilder();
Matcher matcher = GLOB_PATTERN.matcher(pattern);
int end = 0;
while (matcher.find()) {
patternBuilder.append(quote(pattern, end, matcher.start()));
String match = matcher.group();
if ("?".equals(match)) {
patternBuilder.append('.');
}
else if ("*".equals(match)) {
patternBuilder.append(".*");
}
else if (match.startsWith("{") && match.endsWith("}")) {
int colonIdx = match.indexOf(':');
if (colonIdx == -1) {
patternBuilder.append(DEFAULT_VARIABLE_PATTERN);
this.variableNames.add(matcher.group(1));
}
else {
String variablePattern = match.substring(colonIdx + 1, match.length() - 1);
patternBuilder.append('(');
patternBuilder.append(variablePattern);
patternBuilder.append(')');
String variableName = match.substring(1, colonIdx);
this.variableNames.add(variableName);
}
}
end = matcher.end();
}
patternBuilder.append(quote(pattern, end, pattern.length()));
this.pattern = (caseSensitive ? Pattern.compile(patternBuilder.toString()) :
Pattern.compile(patternBuilder.toString(), Pattern.CASE_INSENSITIVE));
}
ArrayList<String> checkForLinkedMedia (String jid, String message, boolean allowWebDownloads)
{
ArrayList<String> results = new ArrayList<>();
Matcher matcher = aesGcmUrlPattern.matcher(message);
while (matcher.find())
{
results.add(matcher.group());
}
if (allowWebDownloads)
{
//if someone sends us a random URL, only get it if it is from the same host as the jabberid
matcher = urlPattern.matcher(message);
if (matcher.find())
{
int matchStart = matcher.start(1);
int matchEnd = matcher.end();
String urlDownload = message.substring(matchStart,matchEnd);
try {
String domain = JidCreate.bareFrom(jid).getDomain().toString();
//remove the conference subdomain when checking a match to the media upload
if (domain.contains("conference."))
domain = domain.replace("conference.","");
if (urlDownload.contains(domain)) {
results.add(urlDownload);
}
}
catch (XmppStringprepException se)
{
//This shouldn't happeN!
}
}
}
return results;
}