Program Club

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

proclub 2020. 11. 2. 20:05
반응형

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


나는 문자열이 있습니다.

String s = "test string (67)";

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

누구든지이 작업을 수행하는 방법을 알려주시겠습니까?


아마 정말 깔끔한 RegExp가있을 것입니다.하지만 저는 그 분야에서 멍청한 사람이므로 대신 ...

String s = "test string (67)";

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

System.out.println(s);

이렇게 해봐

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

하위 문자열에 대한 메서드의 서명은 다음과 같습니다.

s.substring(int start, int end);

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

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

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

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


정규식 사용 :

 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는 정규식을 지원 하지만 실제로 일치를 추출하는 데 사용하려는 경우 다소 번거 롭습니다. 예제에서 원하는 문자열을 얻는 가장 쉬운 방법은 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

한 줄로 다음을 제안합니다.

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

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

아파치 공용 라이브러리의 StringUtils를 사용하여이를 수행 할 수 있습니다.

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

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"

분할 방법을 사용하는 또 다른 방법

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

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

이것은 두 문자 세트 사이에 텍스트를 가져 오려는 더 복잡한 정규식 문제에 도움이 될 수 있습니다.


사용하다 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);

    }

}

String s = "test string (67)";

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

다른 가능한 해결책은 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>>

이를 수행하는 "일반적인"방법은 처음부터 문자열을 구문 분석하고 첫 번째 대괄호 앞의 모든 문자를 버리고 첫 번째 대괄호 뒤에있는 문자를 기록하고 두 번째 대괄호 뒤에있는 문자를 버리는 것입니다.

나는 정규식 라이브러리 또는 그것을 할 무언가가 있다고 확신합니다.


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

Test String test string (67) from which you need to get the String which is nested in-between two Strings.

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.

StringUtils class substringBetween() function gets the String that is nested in between two Strings. 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,}

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

Regular-Expression with the utility class RegexUtils and some functions.
      Pattern.DOTALL: Matches any character, including a line terminator.
      Pattern.MULTILINE: Matches entire String from the start^ till end$ of the input sequence.

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

Please refer below sample. I have created sample as per your requirement

sample : click here


I got the answer like this. Try it

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

참고URL : https://stackoverflow.com/questions/12595019/how-to-get-a-string-between-two-characters

반응형