正则表达式如何在Java中表示字符串的get圆括号部分

正则表达式如何在Java中表示字符串的get圆括号部分,java,regex,Java,Regex,我正在尝试使用正则表达式get圆括号fchar foo (f123&) ff ccc 这是一个测试表示值: (?i)(?您当前的正则表达式模式是\([a-l])\),这将不匹配,因为输入字符串在单字母之后和右括号之前有其他内容。我可以在此处使用字符串#replaceAll作为单行选项: String input = "foo (f123&) ff ccc"; String output = input.replaceAll("^.*\\(([a-l])[^)]*\\).*$",

我正在尝试使用正则表达式get圆括号
f
char

foo (f123&) ff ccc
这是一个测试表示值:


  • (?i)(?您当前的正则表达式模式是
    \([a-l])\)
    ,这将不匹配,因为输入字符串在单字母之后和右括号之前有其他内容。我可以在此处使用
    字符串#replaceAll
    作为单行选项:

    String input = "foo (f123&) ff ccc";
    String output = input.replaceAll("^.*\\(([a-l])[^)]*\\).*$", "$1");
    System.out.println("letter is: " + output);
    
    这张照片是:

    letter is: f
    
    如果需要迭代正则表达式解决方案:

    String input = "foo (f123&) ff ccc";
    String pattern = "\\(([a-l])[^)]*\\)";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(input);
    while (m.find()) {
        System.out.println("MATCH: " + m.group(1));
    }
    

    你所说的
    获取括号f char
    是什么意思?你只想捕获括号中的
    f
    字符或整个数据?@CodeManiac only
    f
    char你当前的正则表达式查找值
    (任何字符a到i)
    你需要更改正则表达式以仅捕获
    f
    \([a-i])[^]*\)
    此处,您所需的数据将在第1组中。如果您不确定f的位置,则需要进一步调整上述正则表达式。i、 e.这将有助于
    \([^a-i]*([a-i])[^]*\\)
    因为我有很多喜欢这个字符串,想想string.replaceAll比regex慢,所以寻找regex express的性能会更好:)@F_uuuuu检查我的更新答案以获得正式的regex解决方案。请注意,内部
    replaceAll
    仅使用
    模式和
    匹配器,因此性能方面应该大致相同。
    
    String input = "foo (f123&) ff ccc";
    String pattern = "\\(([a-l])[^)]*\\)";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(input);
    while (m.find()) {
        System.out.println("MATCH: " + m.group(1));
    }