如何获得两个字符之间的字符串?


93

我有绳子

String s = "test string (67)";

我想得到67号,它是(和)之间的字符串。

谁能告诉我该怎么做?


1
有几种方法-直到你到达你可以遍历字符串中的字符(或找到的第一个指数()与子串,或者大多数人会做,使用正则表达式做到这一点。
Andreas Dolk 2012年

Answers:


102

RegExp可能真的很整洁,但是我在那个领域不是菜鸟,所以...

String s = "test string (67)";

s = s.substring(s.indexOf("(") + 1);
s = s.substring(0, s.indexOf(")"));

System.out.println(s);

4
无需经历正则表达式解析的麻烦,我认为这是提取所需字符串的最佳方法。
verisimilitude 2012年

3
regex到目前为止功能更强大,并且可以在更多情况下使用,但为简单起见,它可以工作...
MadProgrammer 2012年

2
说真的,为什么这会引起反对?它不起作用吗?它不能回答操作问题吗?
MadProgrammer 2015年

如果我有多个值,那么我该如何使用子字符串呢?我有这样的字符串'this is an example of <how><i have it>',我需要在'<'和'>'之间找到值
Vignesh,2018年

@Vignesh使用正则表达式
MadProgrammer

74

一个不需要您执行indexOf的问题的非常有用的解决方案是使用Apache Commons库。

 StringUtils.substringBetween(s, "(", ")");

即使存在多次出现的关闭字符串,此方法也可以让您进行处理,而通过查找indexOf关闭字符串将不容易。

您可以从此处下载此库:https : //mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4


7
还有substringsBetween(...),如果你希望多个结果,这正是我一直在寻找。谢谢
cahen 19'Apr


72

像这样尝试

String s="test string(67)";
String requiredString = s.substring(s.indexOf("(") + 1, s.indexOf(")"));

子字符串的方法签名为:

s.substring(int start, int end);

30

通过使用正则表达式:

 String s = "test string (67)";
 Pattern p = Pattern.compile("\\(.*?\\)");
 Matcher m = p.matcher(s);
 if(m.find())
    System.out.println(m.group().subSequence(1, m.group().length()-1)); 

2
我认为您应该使用“。*?”使其成为非贪婪的匹配。代替。否则,如果字符串soemthing像“测试字符串(67)和(68),这将返回‘67)和(68’
闪灵项目

18

Java支持正则表达式,但是如果您确实想使用它们来提取匹配项,则它们会很麻烦。我认为在示例中获取所需字符串的最简单方法是在String类的replaceAll方法中使用正则表达式支持:

String x = "test string (67)".replaceAll(".*\\(|\\).*", "");
// x is now the String "67"

这只是删除了所有内容,包括第一个(,以及第一个)和之后的所有内容。这只是在括号之间留了东西。

但是,这样做的结果仍然是String。如果您想要一个整数结果,则需要进行另一次转换:

int n = Integer.parseInt(x);
// n is now the integer 67

10

我建议在一行中:

String input = "test string (67)";
input = input.subString(input.indexOf("(")+1, input.lastIndexOf(")"));
System.out.println(input);`

7
String s = "test string (67)";

int start = 0; // '(' position in string
int end = 0; // ')' position in string
for(int i = 0; i < s.length(); i++) { 
    if(s.charAt(i) == '(') // Looking for '(' position in string
       start = i;
    else if(s.charAt(i) == ')') // Looking for ')' position in  string
       end = i;
}
String number = s.substring(start+1, end); // you take value between start and end

7

您可以使用apache公共库的StringUtils来执行此操作。

import org.apache.commons.lang3.StringUtils;
...
String s = "test string (67)";
s = StringUtils.substringBetween(s, "(", ")");
....

7
String result = s.substring(s.indexOf("(") + 1, s.indexOf(")"));

1
请通过缩进4个空格来格式化代码。另外,我将通过解释您的代码为那些不确定.substring和.indexOf`做什么的访问者提供的服务来稍微补充一下您的答案。
Bugs

6

测试String test string (67),您需要从中获取嵌套在两个String之间的String。

String str = "test string (67) and (77)", open = "(", close = ")";

列出了一些可能的方法:简单的通用解决方案:

String subStr = str.substring(str.indexOf( open ) + 1, str.indexOf( close ));
System.out.format("String[%s] Parsed IntValue[%d]\n", subStr, Integer.parseInt( subStr ));

Apache软件基金会commons.lang3

StringUtilssubstringBetween()函数获取嵌套在两个String之间的String。仅返回第一个匹配项。

String substringBetween = StringUtils.substringBetween(subStr, open, close);
System.out.println("Commons Lang3 : "+ substringBetween);

用嵌套在两个字符串之间的字符串替换给定的字符串。 #395


具有正则表达式的模式: (\()(.*?)(\)).*

匹配(几乎)任意字符 .? = .{0,1}, .* = .{0,}, .+ = .{1,}

String patternMatch = patternMatch(generateRegex(open, close), str);
System.out.println("Regular expression Value : "+ patternMatch);

具有实用程序类RegexUtils和某些功能的正则表达式。
      Pattern.DOTALL匹配任何字符,包括行终止符。
      Pattern.MULTILINE从输入序列的开始^到结束匹配整个String $

public static String generateRegex(String open, String close) {
    return "(" + RegexUtils.escapeQuotes(open) + ")(.*?)(" + RegexUtils.escapeQuotes(close) + ").*";
}

public static String patternMatch(String regex, CharSequence string) {
    final Pattern pattern  = Pattern.compile(regex, Pattern.DOTALL);
    final Matcher matcher = pattern .matcher(string);

    String returnGroupValue = null;
    if (matcher.find()) { // while() { Pattern.MULTILINE }
        System.out.println("Full match: " + matcher.group(0));
        System.out.format("Character Index [Start:End]«[%d:%d]\n",matcher.start(),matcher.end());
        for (int i = 1; i <= matcher.groupCount(); i++) {
            System.out.println("Group " + i + ": " + matcher.group(i));
            if( i == 2 ) returnGroupValue = matcher.group( 2 );
        }
    }
    return returnGroupValue;
}

StringUtils非常有用
TuGordoBello

5
public String getStringBetweenTwoChars(String input, String startChar, String endChar) {
    try {
        int start = input.indexOf(startChar);
        if (start != -1) {
            int end = input.indexOf(endChar, start + startChar.length());
            if (end != -1) {
                return input.substring(start + startChar.length(), end);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return input; // return null; || return "" ;
}

用法:

String input = "test string (67)";
String startChar = "(";
String endChar   = ")";
String output = getStringBetweenTwoChars(input, startChar, endChar);
System.out.println(output);
// Output: "67"

4

使用 Pattern and Matcher

public class Chk {

    public static void main(String[] args) {

        String s = "test string (67)";
        ArrayList<String> arL = new ArrayList<String>();
        ArrayList<String> inL = new ArrayList<String>();

        Pattern pat = Pattern.compile("\\(\\w+\\)");
        Matcher mat = pat.matcher(s);

        while (mat.find()) {

            arL.add(mat.group());
            System.out.println(mat.group());

        }

        for (String sx : arL) {

            Pattern p = Pattern.compile("(\\w+)");
            Matcher m = p.matcher(sx);

            while (m.find()) {

                inL.add(m.group());
                System.out.println(m.group());
            }
        }

        System.out.println(inL);

    }

}

2
说出变量名可以使方法更友好。
Zon 2015年

3

使用拆分方法的另一种方法

public static void main(String[] args) {


    String s = "test string (67)";
    String[] ss;
    ss= s.split("\\(");
    ss = ss[1].split("\\)");

    System.out.println(ss[0]);
}

3

我发现使用Regex和Pattern / Matcher类执行此操作的最不通用的方法是:

String text = "test string (67)";

String START = "\\(";  // A literal "(" character in regex
String END   = "\\)";  // A literal ")" character in regex

// Captures the word(s) between the above two character(s)
String pattern = START + "(\w+)" + END;

Pattern pattern = Pattern.compile(pattern);
Matcher matcher = pattern.matcher(text);

while(matcher.find()) {
    System.out.println(matcher.group()
        .replace(START, "").replace(END, ""));
}

这可能有助于解决更复杂的正则表达式问题,您需要在两组字符之间获取文本。


2

“通用”方法是从头开始分析字符串,将所有字符丢在第一个括号之前,将所有字符记录在第一个括号之后,并将字符丢在第二个括号之后。

我敢肯定有一个正则表达式库或一些要做的事情。


Java支持正则表达式。不需要regexp4j库;)
Andreas Dolk 2012年

2
String s = "test string (67)";

System.out.println(s.substring(s.indexOf("(")+1,s.indexOf(")")));

2

另一种可能的解决方案是使用lastIndexOf它将向后查找字符或字符串的位置。

在我的场景中,我有以下关注String,因此我不得不提取<<UserName>>

1QAJK-WKJSH_MyApplication_Extract_<<UserName>>.arc

因此,这indexOfStringUtils.substringBetween没有帮助,因为他们从头开始寻找角色。

所以,我用 lastIndexOf

String str = "1QAJK-WKJSH_MyApplication_Extract_<<UserName>>.arc";
String userName = str.substring(str.lastIndexOf("_") + 1, str.lastIndexOf("."));

而且,它给了我

<<UserName>>

1

像这样:

public static String innerSubString(String txt, char prefix, char suffix) {

    if(txt != null && txt.length() > 1) {

        int start = 0, end = 0;
        char token;
        for(int i = 0; i < txt.length(); i++) {
            token = txt.charAt(i);
            if(token == prefix)
                start = i;
            else if(token == suffix)
                end = i;
        }

        if(start + 1 < end)
            return txt.substring(start+1, end);

    }

    return null;
}


1

如果没有匹配的正则表达式,它将返回原始字符串

var iAm67 = "test string (67)".replaceFirst("test string \\((.*)\\)", "$1");

将匹配项添加到代码中

String str = "test string (67)";
String regx = "test string \\((.*)\\)";
if (str.matches(regx)) {
    var iAm67 = str.replaceFirst(regx, "$1");
}

- -编辑 - -

我使用https://www.freeformatter.com/java-regex-tester.html#ad-output测试正则表达式。

原来最好添加?*之后,以减少匹配次数。像这样的东西:

String str = "test string (67)(69)";
String regx1 = "test string \\((.*)\\).*";
String regx2 = "test string \\((.*?)\\).*";
String ans1 = str.replaceFirst(regx1, "$1");
String ans2 = str.replaceFirst(regx2, "$1");
System.out.println("ans1:"+ans1+"\nans2:"+ans2); 
// ans1:67)(69
// ans2:67
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.