如何在两个字符之间获取字符串?

时间:2022-05-17 17:07:51

I have a string,

我有一个字符串,

String s = "test string (67)";

I want to get the no 67 which is the string between ( and ).

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

Can anyone please tell me how to do this?

有人能告诉我怎么做吗?

17 个解决方案

#1


65  

There's probably a really neat RegExp, but I'm noob in that area, so instead...

这里可能有一个非常整洁的RegExp,但是我在那个领域是新手,所以相反……

String s = "test string (67)";

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

System.out.println(s);

#2


45  

Try it like this

试着这样

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

The method's signature for substring is:

该方法的子串签名如下:

s.substring(int start, int end);

#3


31  

A very useful solution to this issue which doesn't require from you to do the indexOf is using Apache Commons libraries.

这个问题的一个非常有用的解决方案是使用Apache Commons库。

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

This method will allow you even handle even if there multiple occurrences of the closing string which wont be easy by looking for indexOf closing string.

这个方法甚至允许您处理关闭字符串的多次出现,而查找关闭字符串的索引并不容易。

You can download this library from here: https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4

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

#4


19  

By using regular expression :

使用正则表达式:

 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)); 

#5


13  

Java supports Regular Expressions, but they're kind of cumbersome if you actually want to use them to extract matches. I think the easiest way to get at the string you want in your example is to just use the Regular Expression support in the String class's replaceAll method:

Java支持正则表达式,但是如果您想要使用它们来提取匹配,它们就有点麻烦了。我认为要得到示例中的字符串,最简单的方法是使用string类的replaceAll方法中的正则表达式支持:

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

This simply deletes everything up-to-and-including the first (, and the same for the ) and everything thereafter. This just leaves the stuff between the parenthesis.

这只需要删除所有最新的内容,包括第一个(对于这个)以及之后的所有内容。这只剩下括号之间的内容。

However, the result of this is still a String. If you want an integer result instead then you need to do another conversion:

但是,结果仍然是一个字符串。如果你想要一个整数结果,那么你需要做另一个转换:

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

#6


9  

In a single line, I suggest:

在这一行,我建议:

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

#7


6  

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

#8


3  

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

#9


2  

Another way of doing using split method

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

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]);
}

#10


2  

The least generic way I found to do this with Regex and Pattern / Matcher classes:

我发现用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, ""));
}

This may help for more complex regex problems where you want to get the text between two set of characters.

这可能有助于解决更复杂的regex问题,即您希望在两组字符之间获取文本。

#11


2  

Use 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);

    }

}

#12


1  

You could use apache common library's StringUtils to do this.

您可以使用apache公共库的StringUtils实现这一点。

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

#13


1  

The other possible solution is to use lastIndexOf where it will look for character or String from backward.

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

In my scenario, I had following String and I had to extract <<UserName>>

在我的场景中,我有以下字符串,我必须提取 >

1QAJK-WKJSH_MyApplication_Extract_<<UserName>>.arc

So, indexOf and StringUtils.substringBetween was not helpful as they start looking for character from beginning.

所以,indexOf stringutil的。substringBetween没有帮助,因为他们开始寻找性格。

So, I used lastIndexOf

所以,我使用lastIndexOf

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

And, it gives me

它给了我

<<UserName>>

#14


0  

The "generic" way of doing this is to parse the string from the start, throwing away all the characters before the first bracket, recording the characters after the first bracket, and throwing away the characters after the second bracket.

这样做的“通用”方法是从开始解析字符串,将第一个括号前的所有字符丢弃,将第一个括号后的字符记录下来,并将第二个括号后的字符丢弃。

I'm sure there's a regex library or something to do it though.

我肯定有一个regex库或者别的什么东西可以做。

#15


0  

String s = "test string (67)";

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

#16


0  

Something like this:

是这样的:

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;
}

#17


-1  

I got the answer like this. Try it

我得到了这样的答案。试一试

String value = "test string (67)";
int intValue =Integer.valueOf( value.replaceAll("[^0-9]", ""));

#1


65  

There's probably a really neat RegExp, but I'm noob in that area, so instead...

这里可能有一个非常整洁的RegExp,但是我在那个领域是新手,所以相反……

String s = "test string (67)";

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

System.out.println(s);

#2


45  

Try it like this

试着这样

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

The method's signature for substring is:

该方法的子串签名如下:

s.substring(int start, int end);

#3


31  

A very useful solution to this issue which doesn't require from you to do the indexOf is using Apache Commons libraries.

这个问题的一个非常有用的解决方案是使用Apache Commons库。

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

This method will allow you even handle even if there multiple occurrences of the closing string which wont be easy by looking for indexOf closing string.

这个方法甚至允许您处理关闭字符串的多次出现,而查找关闭字符串的索引并不容易。

You can download this library from here: https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4

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

#4


19  

By using regular expression :

使用正则表达式:

 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)); 

#5


13  

Java supports Regular Expressions, but they're kind of cumbersome if you actually want to use them to extract matches. I think the easiest way to get at the string you want in your example is to just use the Regular Expression support in the String class's replaceAll method:

Java支持正则表达式,但是如果您想要使用它们来提取匹配,它们就有点麻烦了。我认为要得到示例中的字符串,最简单的方法是使用string类的replaceAll方法中的正则表达式支持:

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

This simply deletes everything up-to-and-including the first (, and the same for the ) and everything thereafter. This just leaves the stuff between the parenthesis.

这只需要删除所有最新的内容,包括第一个(对于这个)以及之后的所有内容。这只剩下括号之间的内容。

However, the result of this is still a String. If you want an integer result instead then you need to do another conversion:

但是,结果仍然是一个字符串。如果你想要一个整数结果,那么你需要做另一个转换:

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

#6


9  

In a single line, I suggest:

在这一行,我建议:

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

#7


6  

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

#8


3  

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

#9


2  

Another way of doing using split method

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

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]);
}

#10


2  

The least generic way I found to do this with Regex and Pattern / Matcher classes:

我发现用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, ""));
}

This may help for more complex regex problems where you want to get the text between two set of characters.

这可能有助于解决更复杂的regex问题,即您希望在两组字符之间获取文本。

#11


2  

Use 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);

    }

}

#12


1  

You could use apache common library's StringUtils to do this.

您可以使用apache公共库的StringUtils实现这一点。

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

#13


1  

The other possible solution is to use lastIndexOf where it will look for character or String from backward.

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

In my scenario, I had following String and I had to extract <<UserName>>

在我的场景中,我有以下字符串,我必须提取 >

1QAJK-WKJSH_MyApplication_Extract_<<UserName>>.arc

So, indexOf and StringUtils.substringBetween was not helpful as they start looking for character from beginning.

所以,indexOf stringutil的。substringBetween没有帮助,因为他们开始寻找性格。

So, I used lastIndexOf

所以,我使用lastIndexOf

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

And, it gives me

它给了我

<<UserName>>

#14


0  

The "generic" way of doing this is to parse the string from the start, throwing away all the characters before the first bracket, recording the characters after the first bracket, and throwing away the characters after the second bracket.

这样做的“通用”方法是从开始解析字符串,将第一个括号前的所有字符丢弃,将第一个括号后的字符记录下来,并将第二个括号后的字符丢弃。

I'm sure there's a regex library or something to do it though.

我肯定有一个regex库或者别的什么东西可以做。

#15


0  

String s = "test string (67)";

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

#16


0  

Something like this:

是这样的:

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;
}

#17


-1  

I got the answer like this. Try it

我得到了这样的答案。试一试

String value = "test string (67)";
int intValue =Integer.valueOf( value.replaceAll("[^0-9]", ""));