As an example let's imagine I'm searching for a specific group of number inside a name
[3363]Burn the Witch Year 1958
In this case there are 2 groups of number of the same length, and I need to get the one inside the brackets. How can search for a group of number of a specific length, that are inside a brackets without getting the brackets in the answer?
regexChecker("\\[\\d{3,4}\\]",longString);
The output of the example code is [3347]
.
The code im using as practice is:
public class PracticaPatrones {
public static void main(String[] args) {
String longString = "";
String[] Names = {"[3358]Maoujou de Oyasumi 1", "[3347]King's Raid; Ishi wo Tsugumono-tachi 2", "[3363]Burn the Witch 3", "[3283]Hachi-nan tte, Sore wa Nai deshou! 1", "[391]Denpa Onna to Seishun Otoko 1", "[0587] Onii-chan Dakedo Ai Sae Areba Kankeinai yo ne 11", "[870] Onii-chan Dakedo Ai Sae Areba Kankeinai yo ne 11"};
System.out.println(Names.length);
System.out.println("Bandera");
for (int i = 0; i < Names.length; i++) {
longString = Names[i];
regexChecker("\\[\\d{3,4}\\]", longString);
}
}
public static void regexChecker(String theRegex, String str2Check) {
Pattern checkRegex = Pattern.compile(theRegex);
Matcher regexMatcher = checkRegex.matcher(str2Check);
while (regexMatcher.find()) {
if (regexMatcher.group().length() != 0) {
System.out.println(regexMatcher.group().trim());
}
System.out.println("start index : " + regexMatcher.start());
System.out.println("end index : " + regexMatcher.end());
}
}
}
You can use the regex, (?<=\[)\d{3,4}(?=\])
which can be explained as follows:
(?<=\[)
looks behind for [
\d{3,4}
looks for 3 to 4 digits (it's already there in your question)(?=\])
looks ahead for ]
Demo:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("(?<=\\[)\\d{3,4}(?=\\])");
Matcher matcher = pattern.matcher("[3358]Maoujou de Oyasumi 1");
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
Output:
3358
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다