두 문자 사이의 문자열을 얻는 방법?


93

나는 문자열이 있습니다.

String s = "test string (67)";

(와) 사이의 문자열 인 67 번을 얻고 싶습니다.

누구 든지이 방법을 알려주시겠습니까?


1
방법은 여러 가지가 있습니다 - 당신이 도달 할 때까지 문자열의 문자를 반복 할 수 (또는 최초의 인덱스 찾을 수 ()와 나, 대부분의 사람들이 어떻게 할 것인지, 정규 표현식을 사용하는 하위 문자열 함께 할.
Andreas Dolk 2012 년

답변:


103

아마 정말 깔끔한 RegExp가있을 것입니다.하지만 저는 그 영역에서 멍청한 사람입니다.

String s = "test string (67)";

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

System.out.println(s);

4
정규식 구문 분석의 이상 함을 거치지 않고 이것이 필요한 문자열을 추출하는 가장 좋은 방법이라고 생각합니다.
진실성

3
정규식은 훨씬 더 강력한 것입니다 더 많은 경우에 걸릴 수 있지만, 간단하게하기 위해이 작품을 ...
MadProgrammer

2
진지하게, 이것이 왜 반대표를 끌까요? 작동하지 않습니까? 작전 질문에 대답하지 않습니까?
MadProgrammer 2015

여러 값이있는 경우 어떻게 하위 문자열을 사용할 수 있습니까? 내가 이와 같은 문자열이 'this is an example of <how><i have it>'있고 '<'와 '>'사이의 값을 찾아야합니다.이
Vignesh

사용을 정규 표현식 @Vignesh
MadProgrammer

74

이 문제에 대해 indexOf를 수행 할 필요가없는 매우 유용한 솔루션은 Apache Commons 라이브러리를 사용하는 것입니다.

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

이 메서드는 indexOf 닫는 문자열을 찾아서 쉽지 않은 닫는 문자열이 여러 번 발생하더라도 처리 할 수 ​​있습니다.

https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4 에서이 라이브러리를 다운로드 할 수 있습니다.


7
substringsBetween(...)여러 결과를 기대하는 경우 도 있는데 , 이것이 제가 찾던 것입니다. 감사합니다
cahen 2019-04-17


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
". *?"를 사용하여 욕심없는 일치를 만들어야한다고 생각합니다. 대신. 그렇지 않으면 문자열이 "test string (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

아파치 공용 라이브러리의 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

test string (67)두 문자열 사이에 중첩 된 문자열을 가져 오는 데 필요한 테스트 문자열입니다.

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 Software Foundation commons.lang3.

StringUtils클래스 substringBetween()함수는 두 문자열 사이에 중첩 된 문자열을 가져옵니다. 첫 번째 일치 만 반환됩니다.

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: 입력 시퀀스 의 시작 부터 끝까지 전체 문자열일치 합니다.^$

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 2011

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

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 라이브러리가 필요 없음)
안드레아스 돌크

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

그래서, indexOf그리고 StringUtils.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

이것은 간단한 \D+정규식 사용 및 작업입니다.
이것은 숫자를 제외한 모든 문자를 선택하므로 복잡 할 필요가 없습니다.

/\D+/

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
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.