java.lang.String.replaceFirst()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(8.9k)|赞(0)|评价(0)|浏览(122)

本文整理了Java中java.lang.String.replaceFirst()方法的一些代码示例,展示了String.replaceFirst()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。String.replaceFirst()方法的具体详情如下:
包路径:java.lang.String
类名称:String
方法名:replaceFirst

String.replaceFirst介绍

[英]Replaces the first substring of this string that matches the given regular expression with the given replacement.

An invocation of this method of the form str.replaceFirst(regex, repl) yields exactly the same result as the expression

java.util.regex.Pattern. java.util.regex.Pattern#compile(regex). java.util.regex.Pattern#matcher(java.lang.CharSequence)(str). java.util.regex.Matcher#replaceFirst(repl)

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see java.util.regex.Matcher#replaceFirst. Use java.util.regex.Matcher#quoteReplacement to suppress the special meaning of these characters, if desired.
[中]将此字符串中与给定{$0$}匹配的第一个子字符串替换为给定的替换项。
调用str.replaceFirst(regex,repl)形式的此方法会产生与表达式完全相同的结果
JAVAutil。正则表达式。图案JAVAutil。正则表达式。模式#编译(regex)。JAVAutil。正则表达式。模式匹配器(java.lang.CharSequence)(str)。JAVAutil。正则表达式。匹配器#替换优先(repl)
请注意,替换字符串中的反斜杠(\)和美元符号($)可能会导致结果不同于将其视为文字替换字符串时的结果;参见java。util。正则表达式。Matcher#先替换。使用java。util。正则表达式。Matcher“quoteReplacement,如果需要,用于抑制这些字符的特殊含义。

代码示例

代码示例来源:origin: org.mockito/mockito-core

/**
 * @param text
 *            to have the first line removed
 * @return less first line
 */
public static String removeFirstLine(String text) {
  return text.replaceFirst(".*?\n", "");
}

代码示例来源:origin: jenkinsci/jenkins

static String trimVersion(String version) {
  // TODO seems like there should be some trick with VersionNumber to do this
  return version.replaceFirst(" .+$", "");
}

代码示例来源:origin: jenkinsci/jenkins

@Override
public String getIconFilePathPattern() {
  return (Jenkins.RESOURCE_PATH + "/images/:size/freestyleproject.png").replaceFirst("^/", "");
}

代码示例来源:origin: google/j2objc

/**
   * @param text to have the first line removed
   * @return less first line
   */
  public String of(String text) {
    return text.replaceFirst(".*?\n", "");
  }
}

代码示例来源:origin: stackoverflow.com

String[] in = {
  "01234",         // "[1234]"
  "0001234a",      // "[1234a]"
  "101234",        // "[101234]"
  "000002829839",  // "[2829839]"
  "0",             // "[0]"
  "0000000",       // "[0]"
  "0000009",       // "[9]"
  "000000z",       // "[z]"
  "000000.z",      // "[.z]"
};
for (String s : in) {
  System.out.println("[" + s.replaceFirst("^0+(?!$)", "") + "]");
}

代码示例来源:origin: Netflix/eureka

@Override
  public String next() {
    String value = internalIterator.next();
    return value.replaceFirst(prefixRegex, "");
  }
};

代码示例来源:origin: jenkinsci/jenkins

/**
 * @param target something like {@code http://jenkins/cli?remoting=true}
 *               which we then need to split into {@code http://jenkins/} + {@code cli?remoting=true}
 *               in order to construct a crumb issuer request
 * @deprecated use {@link #FullDuplexHttpStream(URL, String, String)} instead
 */
@Deprecated
public FullDuplexHttpStream(URL target, String authorization) throws IOException {
  this(new URL(target.toString().replaceFirst("/cli.*$", "/")), target.toString().replaceFirst("^.+/(cli.*)$", "$1"), authorization);
}

代码示例来源:origin: alibaba/arthas

private static String format(String from, Object... arguments) {
  if (from != null) {
    String computed = from;
    if (arguments != null && arguments.length != 0) {
      for (Object argument : arguments) {
        computed = computed.replaceFirst("\\{\\}", Matcher.quoteReplacement(argument.toString()));
      }
    }
    return computed;
  }
  return null;
}

代码示例来源:origin: apache/incubator-dubbo

/**
 * The format is '{group}/{interfaceName/path}*{version}'
 *
 * @return
 */
public String getEncodedServiceKey() {
  String serviceKey = this.getServiceKey();
  serviceKey = serviceKey.replaceFirst("/", "*");
  return serviceKey;
}

代码示例来源:origin: apache/incubator-dubbo

/**
 * The format is '{group}/{interfaceName/path}*{version}'
 *
 * @return
 */
public String getEncodedServiceKey() {
  String serviceKey = this.getServiceKey();
  serviceKey = serviceKey.replaceFirst("/", "*");
  return serviceKey;
}

代码示例来源:origin: stanfordnlp/CoreNLP

/** Normalize all number tokens to <num> in order to allow
 *  for proper scoring of MSTParser productions.
 */
static protected String normalizeNumbers(String token) {
 String norm = token.replaceFirst("^([0-9]+)-([0-9]+)$", "<num>-$2");
 if (!norm.equals(token)) {
  System.err.printf("Normalized numbers in token: %s => %s\n", token, norm);
 }
 return token;
}

代码示例来源:origin: stanfordnlp/CoreNLP

private static List<String[]> makeSVMLightLineInfos(List<String> lines) {
 List<String[]> lineInfos = new ArrayList<>(lines.size());
 for (String line : lines) {
  line = line.replaceFirst("#.*$", ""); // remove any trailing comments
  // in principle, it'd be nice to save the comment, though, for possible use as a displayedColumn - make it column 1??
  lineInfos.add(line.split("\\s+"));
 }
 return lineInfos;
}

代码示例来源:origin: apache/flink

private static ClassReader getClassReader(Class<?> cls) {
  String className = cls.getName().replaceFirst("^.*\\.", "") + ".class";
  try {
    return new ClassReader(cls.getResourceAsStream(className));
  } catch (IOException e) {
    throw new RuntimeException("Could not create ClassReader: " + e.getMessage(), e);
  }
}

代码示例来源:origin: spring-projects/spring-framework

private Method getGetterFromSetter(Method setter) {
  String getterName = setter.getName().replaceFirst("set", "get");
  try {
    return setter.getDeclaringClass().getMethod(getterName);
  }
  catch (NoSuchMethodException ex) {
    // must be write only
    return null;
  }
}

代码示例来源:origin: prestodb/presto

private static String fixTpchQuery(String s)
  {
    s = s.replaceFirst("(?m);$", "");
    s = s.replaceAll("(?m)^:[xo]$", "");
    s = s.replaceAll("(?m)^:n -1$", "");
    s = s.replaceAll("(?m)^:n ([0-9]+)$", "LIMIT $1");
    s = s.replace("day (3)", "day"); // for query 1
    return s;
  }
}

代码示例来源:origin: jenkinsci/jenkins

public boolean isForNewerHudson() {
  try {
    return requiredCore!=null && new VersionNumber(requiredCore).isNewerThan(
     new VersionNumber(Jenkins.VERSION.replaceFirst("SHOT *\\(private.*\\)", "SHOT")));
  } catch (NumberFormatException nfe) {
    return true;  // If unable to parse version
  }
}

代码示例来源:origin: redisson/redisson

@Override
  public String toString() {
    StringBuilder stringBuilder = new StringBuilder(Modifier.toString(getModifiers()));
    if (getModifiers() != EMPTY_MASK) {
      stringBuilder.append(' ');
    }
    stringBuilder.append(isVarArgs()
        ? getType().asErasure().getName().replaceFirst("\\[\\]$", "...")
        : getType().asErasure().getName());
    return stringBuilder.append(' ').append(getName()).toString();
  }
}

代码示例来源:origin: libgdx/libgdx

private void newArrayC () {
  p("public Object newArray (Type t, int size) {");
  p("    if (t != null) {");
  SwitchedCodeBlock pc = new SwitchedCodeBlock("t.id");
  for (JType type : types) {
    if (type.getQualifiedSourceName().equals("void")) continue;
    if (type.getQualifiedSourceName().endsWith("Void")) continue;
    String arrayType = type.getErasedType().getQualifiedSourceName() + "[size]";
    if (arrayType.contains("[]")) {
      arrayType = type.getErasedType().getQualifiedSourceName();
      arrayType = arrayType.replaceFirst("\\[\\]", "[size]") + "[]";
    }
    pc.add(typeNames2typeIds.get(type.getQualifiedSourceName()), "return new " + arrayType + ";");
  }
  pc.print();
  p("    }");
  p("    throw new RuntimeException(\"Couldn't create array\");");
  p("}");
}

代码示例来源:origin: libgdx/libgdx

private void newArrayC () {
  p("public Object newArray (Type t, int size) {");
  p("    if (t != null) {");
  SwitchedCodeBlock pc = new SwitchedCodeBlock("t.id");
  for (JType type : types) {
    if (type.getQualifiedSourceName().equals("void")) continue;
    if (type.getQualifiedSourceName().endsWith("Void")) continue;
    String arrayType = type.getErasedType().getQualifiedSourceName() + "[size]";
    if (arrayType.contains("[]")) {
      arrayType = type.getErasedType().getQualifiedSourceName();
      arrayType = arrayType.replaceFirst("\\[\\]", "[size]") + "[]";
    }
    pc.add(typeNames2typeIds.get(type.getQualifiedSourceName()), "return new " + arrayType + ";");
  }
  pc.print();
  p("    }");
  p("    throw new RuntimeException(\"Couldn't create array\");");
  p("}");
}

代码示例来源:origin: Netflix/eureka

@Override
  public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException {
    String encodedString = encodingCodec.encode(instanceInfo);
    // convert the field from the json string to what the legacy json would encode as
    encodedString = encodedString.replaceFirst("lastRenewalTimestamp", "renewalTimestamp");
    InstanceInfo decodedValue = decodingCodec.decode(encodedString, InstanceInfo.class);
    assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue, new EurekaEntityComparators.RawIdEqualFunc()), is(true));
    assertThat(EurekaEntityComparators.equal(instanceInfo, decodedValue), is(true));
  }
};

相关文章

微信公众号

最新文章

更多