• 【Java面试宝典】正则表达式



    ● 请你谈谈Java中是如何支持正则表达式操作的?
    考察点:正则表达式

    参考回答:
    Java中的String类提供了支持正则表达式操作的方法,包括:matches()、replaceAll()、replaceFirst()、split()。此外,Java中可以用Pattern类表示正则表达式对象,它提供了丰富的API进行各种正则表达式操作,如:

    面试题: - 如果要从字符串中截取第一个英文左括号之前的字符串,例如:北京市(朝阳区)(西城区)(海淀区),截取结果为:北京市,那么正则表达式怎么写?

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class RegExpTest {
            public static void main(String[] args) {
                String str = "成都市(成华区)(武侯区)(高新区)";
                Pattern p = Pattern.compile(".*?(?=\()");
                Matcher m = p.matcher(str);
                if(m.find()) {
                    System.out.println(m.group()); //成都市
                }
            }
    }
    

    完全看不懂,慢慢查阅资料

    正则表达式-语法

    https://www.runoob.com/regexp/regexp-syntax.html
    菜鸟教程
    大学最好的老师教过我们Linux基础,有讲过正则,所以我就略过。

    正则表达式是由普通字符(例如字符 a 到 z)以及特殊字符(称为"元字符")组成的文字模式。模式描述在搜索文本时要匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配。

    Pattern.compile方法

    易佰教程
    https://www.yiibai.com/javaregex/javaregex_pattern_compile.html

    java.util.regex.Pattern.compile(String regex)方法将给定的正则表达式编译为模式
    声明
    以下是java.util.regex.Pattern.compile(String regex)方法的声明。

    public static Pattern compile(String regex)
    

    参数

    • regex - 要编译的表达式。

    异常

    • PatternSyntaxException - 如果表达式的语法无效。
      示例
      以下示例显示了java.util.regex.Pattern.compile(String regex)方法的用法。
    import java.util.regex.MatchResult;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class PatternDemo {
       private static final String REGEX = "(.*)(\d+)(.*)";
       private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";
    
       public static void main(String[] args) {
          // create a pattern
          Pattern pattern = Pattern.compile(REGEX);
    
          // get a matcher object
          Matcher matcher = pattern.matcher(INPUT); 
    
          if(matcher.find()) {
             //get the MatchResult Object 
             MatchResult result = matcher.toMatchResult();
    
             //Prints the offset after the last character matched.
             System.out.println("First Capturing Group - Match String end(): "+result.end());         
          }
       }
    }//原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/javaregex/javaregex_pattern_compile.html
    

    编译并运行上面的程序,这将产生以下结果

    First Capturing Group - Match String end(): 53
    
  • 相关阅读:
    图解 Cisco IOS 命名规范
    2008北京奥运会足球赛程(男足)
    使用VPC在dynamips环境中模拟PC
    转:MSN反监听及其信息加密技巧!
    活动目录中用户和联系人有变化,但是outlook中的全局地址薄没有反映当前变化
    IE7 的安全警告
    exchange 路由组,管理组,存储组
    中式与西式网页设计的差别http://www.backboneitgroup.com/chinasearchdifferences.htm
    非常清晰的Cisco PIX Syslog 配置说明
    采用Cisco 2600系列替换Cisco 2500系列
  • 原文地址:https://www.cnblogs.com/guoxinyu/p/java-interview-treasure-book-1.html
Copyright © 2020-2023  润新知