나는 문자열이 있습니다.
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);
'this is an example of <how><i have it>'있고 '<'와 '>'사이의 값을 찾아야합니다.이
이 문제에 대해 indexOf를 수행 할 필요가없는 매우 유용한 솔루션은 Apache Commons 라이브러리를 사용하는 것입니다.
StringUtils.substringBetween(s, "(", ")");
이 메서드는 indexOf 닫는 문자열을 찾아서 쉽지 않은 닫는 문자열이 여러 번 발생하더라도 처리 할 수 있습니다.
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4 에서이 라이브러리를 다운로드 할 수 있습니다.
substringsBetween(...)여러 결과를 기대하는 경우 도 있는데 , 이것이 제가 찾던 것입니다. 감사합니다
이렇게 해봐
String s="test string(67)";
String requiredString = s.substring(s.indexOf("(") + 1, s.indexOf(")"));
하위 문자열에 대한 메서드의 서명은 다음과 같습니다.
s.substring(int start, int end);
정규식 사용 :
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 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
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;
}
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"
사용하다 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);
}
}
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, ""));
}
이것은 두 문자 세트 사이에 텍스트를 가져 오려는 더 복잡한 정규식 문제에 도움이 될 수 있습니다.
이 작업을 수행하는 "일반적인"방법은 처음부터 문자열을 구문 분석하고 첫 번째 대괄호 앞의 모든 문자를 버리고 첫 번째 대괄호 뒤에있는 문자를 기록하고 두 번째 대괄호 뒤에있는 문자를 버리는 것입니다.
나는 정규식 라이브러리 또는 그것을 할 무언가가 있다고 확신합니다.
다른 가능한 해결책은 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>>
이 같은:
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;
}
정규식과 일치하지 않으면 원래 문자열을 반환합니다.
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
(또는 최초의 인덱스 찾을 수(와)와 나, 대부분의 사람들이 어떻게 할 것인지, 정규 표현식을 사용하는 하위 문자열 함께 할.