简体   繁体   English

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

[英]How to get a string between two characters?

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?谁能告诉我如何做到这一点?

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

A very useful solution to this issue which doesn't require from you to do the indexOf is using Apache Commons libraries.这个问题的一个非常有用的解决方案是使用Apache Commons库,它不需要您执行 indexOf。

 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.即使通过查找 indexOf 结束字符串多次出现结束字符串,此方法也将允许您处理。

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-lang3/3.4

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

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

Java supports Regular Expressions , but they're kind of cumbersome if you actually want to use them to extract matches. Java 支持正则表达式,但如果您真的想使用它们来提取匹配项,它们会有点麻烦。 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:我认为在示例中获取所需字符串的最简单方法是在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 .但是,这样做的结果仍然是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

In a single line, I suggest:在一行中,我建议:

String input = "test string (67)";
input = input.subString(input.indexOf("(")+1, input.lastIndexOf(")"));
System.out.println(input);`
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

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, "(", ")");
....

Test String test string (67) from which you need to get the String which is nested in-between two Strings.测试字符串test string (67) ,您需要从中获取嵌套在两个字符串之间的字符串。

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

Listed some possible ways : Simple Generic Solution:列出了一些可能的方法:简单的通用解决方案:

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 Software Foundation commons.lang3 . Apache 软件基金会commons.lang3

StringUtils class substringBetween() function gets the String that is nested in between two Strings. StringUtilssubstringBetween()函数获取嵌套在两个字符串之间的字符串。 Only the first match is returned.仅返回第一个匹配项。

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

Replaces the given String, with the String which is nested in between two Strings.用嵌套在两个字符串之间的字符串替换给定的字符串。 #395


Pattern with Regular-Expressions: (\\()(.*?)(\\)).*正则表达式模式: (\\()(.*?)(\\)).*

The Dot Matches (Almost) Any Character .? = .{0,1}, .* = .{0,}, .+ = .{1,}匹配(几乎)任何字符.? = .{0,1}, .* = .{0,}, .+ = .{1,} .? = .{0,1}, .* = .{0,}, .+ = .{1,}

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

Regular-Expression with the utility class RegexUtils and some functions.带有实用程序类RegexUtils和一些函数的正则表达式。
Pattern.DOTALL : Matches any character, including a line terminator. Pattern.DOTALL匹配任何字符,包括行终止符。
Pattern.MULTILINE : Matches entire String from the start ^ till end $ of the input sequence. Pattern.MULTILINE匹配从输入序列的开始^到结束$的整个字符串。

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;
}
String result = s.substring(s.indexOf("(") + 1, s.indexOf(")"));
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 "" ;
}

Usage :用法 :

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

Another way of doing using split method使用 split 方法的另一种方法

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

Use Pattern and Matcher使用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);

    }

}

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.这可能有助于解决更复杂的正则表达式问题,您希望在两组字符之间获取文本。

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.我确定有一个正则表达式库或可以做的事情。

String s = "test string (67)";

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

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>>在我的场景中,我有以下String ,我不得不提取<<UserName>>

1QAJK-WKJSH_MyApplication_Extract_<<UserName>>.arc

So, indexOf and StringUtils.substringBetween was not helpful as they start looking for character from beginning.因此, indexOfStringUtils.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>>

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

it will return original string if no match regex如果没有匹配正则表达式,它将返回原始字符串

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

add matches to the code向代码添加匹配项

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

---EDIT--- - -编辑 - -

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

turn out it's better to add ?原来最好添加? after * for less match.在 * 之后减少匹配。 something like this:像这样:

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

This is a simple use \\D+ regex and job done.这是一个简单的使用\\D+正则表达式并完成工作。
This select all chars except digits, no need to complicate这选择除数字以外的所有字符,无需复杂化

/\D+/

Please refer below sample. 请参考下面的示例。 I have created sample as per your requirement 我根据您的要求创建了样本

sample : click here 样品: 点击这里

String s = "(69)";
System.out.println(s.substring(s.lastIndexOf('(')+1,s.lastIndexOf(')')));

Little extension to top (MadProgrammer) answer小扩展到顶部(MadProgrammer)答案

 public static String getTextBetween(final String wholeString, final String str1, String str2){
    String s = wholeString.substring(wholeString.indexOf(str1) + str1.length());
    s = s.substring(0, s.indexOf(str2));
    return s;
}

I got the answer like this. 我得到了这样的答案。 Try it 试试吧

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM