【问题标题】:Java split and replace a string with valueJava拆分并用值替换字符串
【发布时间】:2013-04-26 11:27:37
【问题描述】:

我有一个以下字符串,我必须在某些条件下拆分并替换该值

http://localhost:8080/api/upload/form/{uploadType}/{uploadName}

我必须只替换 {uploadType}/{uploadName} 的值。我真的不知道如何用价值替换它们。

{uploadType}/{uploadName} 中的字符串可以是任何类型的替换。

我尝试过类似以下的方法:

包 com.test.poc;

public class TestString {
public static void main(String[] args) throws ClassNotFoundException {
    String toBeFixed = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}"; 
    String[] toReplaceWith =toBeFixed.split("{");
for (String string : toReplaceWith) {
    System.out.println("string : "+string);
}   
}

}

但我得到以下异常:

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
{
    at java.util.regex.Pattern.error(Pattern.java:1713)
    at java.util.regex.Pattern.closure(Pattern.java:2775)
    at java.util.regex.Pattern.sequence(Pattern.java:1889)
    at java.util.regex.Pattern.expr(Pattern.java:1752)
    at java.util.regex.Pattern.compile(Pattern.java:1460)
    at java.util.regex.Pattern.<init>(Pattern.java:1133)
    at java.util.regex.Pattern.compile(Pattern.java:823)
    at java.lang.String.split(String.java:2292)
    at java.lang.String.split(String.java:2334)
    at com.test.poc.TestString.main(TestString.java:9)

编辑:

这是我根据Sean Patrick Floyd答案尝试的方法

public String doPOSTPathVariable(String uri,List paramsList) throws IllegalArgumentException, IllegalAccessException, InstantiationException, Exception{
        String uriString="";
        UriComponents uriComponents = UriComponentsBuilder.fromUriString(uri).build();
        for (int j = 0; j<= paramsList.size(); j++) {
            System.out.println("path variable");
            MethodParams methodParams;
            methodParams =(MethodParams) paramsList.get(j);

            if(methodParams.isPrimitive() && methodParams.getDataType()=="boolean"){
                  uriString = uriComponents.expand(true).encode().toUriString();
            }
            if(methodParams.isPrimitive() && methodParams.getDataType()=="java.math.BigDecimal"){
                uriString = uriComponents.expand(123).encode().toUriString();
            }
            if(methodParams.isPrimitive() && methodParams.getDataType()=="java.lang.String"){
                uriString = uriComponents.expand("hexgen").encode().toUriString();
            }
       } 
        return uriString;
    }

但我得到以下异常:

java.lang.IllegalArgumentException: Not enough variable values available to expand 'uploadName'
    at org.springframework.web.util.UriComponents$VarArgsTemplateVariables.getValue(UriComponents.java:1025)
    at org.springframework.web.util.UriComponents.expandUriComponent(UriComponents.java:443)
    at org.springframework.web.util.UriComponents.access$1(UriComponents.java:431)
    at org.springframework.web.util.UriComponents$FullPathComponent.expand(UriComponents.java:800)
    at org.springframework.web.util.UriComponents.expandInternal(UriComponents.java:413)
    at org.springframework.web.util.UriComponents.expand(UriComponents.java:404)
    at com.hexgen.tools.HexgenClassUtils.doPOSTPathVariable(HexgenClassUtils.java:208)
    at com.hexgen.reflection.HttpClientRequests.handleHTTPRequest(HttpClientRequests.java:77)
    at com.hexgen.reflection.HexgenWebAPITest.main(HexgenWebAPITest.java:115)

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 只在运行时扣除要替换的参数个数

标签: java string split


【解决方案1】:

{ 是用于范围重复的正则表达式 meta-character

在此之前

toBeFixed = toBeFixed.replaceAll("\\{", "\n");   

另见文档:http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

类似问题:Java String ReplaceAll method giving illegal repetition error?

【讨论】:

  • http://localhost:8080/api/upload/form/ uploadType}/ uploadName} 是如果我按照你的代码输出,我如何用值替换这两个
【解决方案2】:

也许是UriBuilder

UriBuilder.fromPath("http://localhost:8080/api/upload/form/{uploadType}/{uploadName}").build("foo", "bar");

(碰巧使用您正在使用的确切格式)

【讨论】:

  • 只在运行时扣除要替换的参数个数
  • UriBuilder 是一种构建器模式,您可以使用其返回自身的便捷方法迭代地向其中添加组件。它存在于您的情况与您的情况完全一样,比正则表达式干净得多。
【解决方案3】:

你可以试试这个:

public class TestString {
public static void main(String[] args) throws ClassNotFoundException {
String toBeFixed = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}"; 
String[] toReplaceWith =toBeFixed.split("\\{");
for (String string : toReplaceWith) {
System.out.println("string : "+string);
}   
}

}

【讨论】:

    【解决方案4】:

    如果您使用 Spring MVC,此功能开箱即用 with the new URI builder technology

    UriComponents uriComponents =
        UriComponentsBuilder.fromUriString(
            "http://example.com/hotels/{hotel}/bookings/{booking}").build();
    
    URI uri = uriComponents.expand("42", "21").encode().toUri();
    // or:
    String uriString = uriComponents.expand("42", "21").encode().toUriString();
    

    (事实上你仍然可以使用这项技术,即使你不使用 Spring MVC,但显然你需要在 Classpath 上有 Spring MVC jar)

    【讨论】:

    • 我已关注您的意见,但它给了我java.lang.IllegalArgumentException: Not enough variable values available to expand 'uploadName' 将立即更新问题
    • @Anto 这个方法只有在编译时知道参数个数的情况下才有效
    【解决方案5】:

    UrlBuilder 是解决方案,但如果您只是查看分隔符,您也可以使用子字符串:

    String url = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}";
    int lastSlash = url.lastIndexOf('/');
    int secondLastSlash = url.substring(0, lastSlash).lastIndexOf('/');
    System.out.println(url.substring(secondLastSlash+1, lastSlash));
    System.out.println(url.substring(lastSlash+1));
    

    要删除花括号,可以在字符串上使用 String.replace('{', '') 和 String.replace('}', '')

    【讨论】:

      猜你喜欢
      • 2012-03-22
      • 1970-01-01
      • 2021-05-31
      • 2020-11-26
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 2016-07-07
      • 2016-03-23
      相关资源
      最近更新 更多