yanhj2006
V2EX  ›  Java

咨询 Java 正则提取

  •  
  •   yanhj2006 · Oct 11, 2018 · 3932 views
    This topic created in 2963 days ago, the information mentioned may be changed or developed.

    有类似域名,s1.a1.apple.com.abc.com ,s1.a1.apple.com 想提取s1.a1.apple.com,即从前开始优先匹配的正常域名,尝试这样 java 中用正则 ([\w\-]*\.?)+\.(com|cn|net|org)

     while (matcher.find())
       matcher.group
    

    一直提取是是全域名,求正确的正则

    10 replies  •  2018-10-15 13:47:44 +08:00
    xuhaoyangx
    xuhaoyangx
    Oct 11, 2018
    1
    你是不是用错了。
    anyele
    anyele
    Oct 11, 2018 via Android
    2
    @xuhaoyangx 这是什么字体
    onexpiece
    onexpiece
    Oct 11, 2018
    3
    (?:\.?[\w\-]*)+?\.(?:com|cn|net|org)
    yanhj2006
    yanhj2006
    OP
    Oct 11, 2018
    4
    @onexpiece 关键是?的非贪心模式,谢谢
    xuhaoyangx
    xuhaoyangx
    Oct 12, 2018
    5
    @anyele #2 mac os 自带
    970749518nkq
    970749518nkq
    Oct 12, 2018 via Android
    6
    @anyele Monaco
    Droi
    Droi
    Oct 12, 2018
    7
    用 perl 写的,不知道 java 有用不
    $var = "s1.a1.apple.com.abc.com";

    $var =~ m/((?>[\w.]+(?>(com|net|org|cn)(?=[\.\\])))|([\w.]+(com|net|cn|org)))/;

    print "$1";
    tamer
    tamer
    Oct 12, 2018
    8
    [\\w\\-]
    这\w 后的\-是个什么意思?...没见过这种语法呢, 有没老哥给解个惑
    Droi
    Droi
    Oct 12, 2018
    9
    重新改了下
    $var =~ m/(([\w.]+(?>\.(com|net|org|cn)(?=[\.\/])))|([\w.]+\.(com|net|cn|org)))/;
    但是无法匹配 s1.a1com.org.aaa.net.bb.com 成 s1.a1com.org
    thinkmore
    thinkmore
    Oct 15, 2018
    10
    @tamer 我的理解是这样的,-这个字符放在中间应该是区间的意思,但是指向表明这一个字符,所以用了转义吧。
    或者这样写就好理解了[-\\w]
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1875 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 15:12 · PVG 23:12 · LAX 07:12 · JFK 10:12
    ♥ Do have faith in what you're doing.