简体   繁体   中英

Ignoring text between parenthesis in Regex

My goal is to read in the String and ignore the text in parenthesis.

public static void main(String[] args) {
    Pattern checkRegex= Pattern.compile("([a-zA-Z]{3,30}\\s*){2}");

    Matcher regexMatcher=checkRegex.matcher("James Hunt(Skateboarder)");

    while(regexMatcher.find()){
    System.out.println(regexMatcher.group().trim());
}

The current output is:

James Hunt

Skateboarder

Essentially what I want is for the output to be only "James Hunt". What is a suitable Regex pattern to use in this type of situation?

This will work for all non-nested parentheses in your given String:

String input = "James Hunt(Skateboarder)";
String output = input.replaceAll("\\([^)]*?\\)", "");

Essentially what I want is for the output to be only "James Hunt". What is a suitable Regex pattern to use in this type of situation?

try regex: ^[^(]*

If you don't have to use regex you can get your data with one simple iteration

String data="some (sentence (with) nested) paranhesis";
StringBuilder buffer=new StringBuilder();
int parenthesisCounter=0;
for (char c:data.toCharArray()){
    if (c=='(') parenthesisCounter++;
    if (c==')') parenthesisCounter--;
    if (c!=')' && c!='(' && parenthesisCounter==0)
        buffer.append(c);
}
System.out.println(buffer);

output:

some  paranhesis

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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