search
HomeJavajavaTutorialJava tries to extract the publishing time of the web page as accurately as possible

对网页中各种不同格式的发布时间进行抽取,将发布时间以规整的“yyyy-MM-dd HH:mm:ss”格式表示出来,只能尽量追求精确,但是因为网络发布时间的格式十分灵活,所以做不到百分百地正确抽取

package whu.extract.pubtime.core;
 
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import whu.utils.TimeUtil;
 
/**
 * Created On 2014年3月13日 下午2:49:05
 * @description 获取网页的发布时间 
 */
public class FetchPubTime {
    /** 表示url中连续的8位日期,例如http://www.baidu.com/20140311/2356.html */
    private static String url_reg_whole= "([-|/|_]{1}20\\d{6})";
    /** 表示 用-或者/隔开的日期,有年月日的,例如 http://www.baidu.com/2014-3-11/2356.html  */
    private static String url_reg_sep_ymd = "([-|/|_]{1}20\\d{2}[-|/|_]{1}\\d{1,2}[-|/|_]{1}\\d{1,2})";
    /** 表示 用-或者/隔开的日期,只有年和月份的,例如 http://www.baidu.com/2014-3/2356.html  */
    private static String url_reg_sep_ym = "([-|/|_]{1}20\\d{2}[-|/|_]{1}\\d{1,2})";
    private static Calendar current = Calendar.getInstance();
    /** 格式正确的时间正则表达式*/
    private static String rightTimeReg = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
     
    /**
     * @param url
     * @param urlContent
     * @return
     */
    public static String getPubTimeVarious(String url,String urlContent) {
         
        String pubTime = getPubTimeFromUrl(url);
         
      //链接里面没有,匹配文本中的
        if(pubTime == null)
        {
            if(urlContent!=null&&!urlContent.trim().equals(""))
                return extractPageDate(urlContent);
        }
         
        return pubTime;
    }
     
    /**从url里面抽取出发布时间,返回YYYY-MM-DD HH:mm:ss格式的字符串
     * @param url
     * @return
     */
    public static String getPubTimeFromUrl(String url)
    {
        Pattern p_whole = Pattern.compile(url_reg_whole);
        Matcher m_whole = p_whole.matcher(url);
        if(m_whole.find(0)&&m_whole.groupCount()>0)
        {
           String time =  m_whole.group(0);
           time = time.substring(1,time.length());
           //每一步都不能够超出当前时间          
        if(current.compareTo(TimeUtil.strToCalendar(time, "yyyyMMdd"))>=0)
        {
 
           return time.substring(0,4)+"-"+time.substring(4,6)+"-"+
                  time.substring(6,8)+" "+"00:00:00";
        }
        }
       
        p_whole = null;
        m_whole = null;
        Pattern p_sep = Pattern.compile(url_reg_sep_ymd);
        Matcher m_sep = p_sep.matcher(url);
        if(m_sep.find(0)&&m_sep.groupCount()>0)
        {
             String time =  m_sep.group(0);
             time = time.substring(1,time.length());
             String[] seg = time.split("[-|/|_]{1}");
             Calendar theTime = Calendar.getInstance();
             theTime.set(Calendar.YEAR,Integer.parseInt(seg[0]));
             theTime.set(Calendar.MONTH, Integer.parseInt(seg[1]));
             theTime.set(Calendar.DAY_OF_MONTH, Integer.parseInt(seg[2]));
             if(current.compareTo(theTime)>=0)
                {
             
            return seg[0]+"-"+seg[1]+"-"+seg[2]+" "+"00:00:00";
                }
        }
        p_sep = null;
        m_sep = null;
        Pattern p_sep_ym = Pattern.compile(url_reg_sep_ym);
        Matcher m_sep_ym = p_sep_ym.matcher(url);
        if(m_sep_ym.find(0)&&m_sep_ym.groupCount()>0)
        {
             String time =  m_sep_ym.group(0);
             time = time.substring(1,time.length());
             Calendar theTime = Calendar.getInstance();
             String[] seg = time.split("[-|/|_]{1}");
             theTime.set(Calendar.YEAR,Integer.parseInt(seg[0]));
             theTime.set(Calendar.MONTH, Integer.parseInt(seg[1]));
             theTime.set(Calendar.DAY_OF_MONTH, 1);
             if(current.compareTo(theTime)>=0)
            {
              
            return seg[0]+"-"+seg[1]+"-"+"01"+" "+"00:00:00";
            }
        }
         
        return null;
    }
     
 
    /** 从网页源码中取出发布时间
     *  java中正则表达式提取字符串中日期实现代码
     *  2013年12月19日15:58:42
     *  读取出2013-12-19 15:48:33或者2013-12-19或者2012/3/05形式的时间
     * @param text 待提取的字符串
     * @return 返回日期
     * @author: oschina
     * @Createtime: Jan 21, 2013
     */
    public static String extractPageDate(String text) { 
        boolean  containsHMS =false;
        String dateStr = text.replaceAll("r?n", " ");
        try { 
            List matches = null; 
            Pattern p_detail = Pattern.compile("(20\\d{2}[-/]\\d{1,2}[-/]\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2})|(20\\d{2}年\\d{1,2}月\\d{1,2}日)", Pattern.CASE_INSENSITIVE|Pattern.MULTILINE); 
            //如果是仅仅抽取年月日,则按照上面的,如果是抽取年月日-时分秒,则按照下面的
            Pattern p = Pattern.compile("(20\\d{2}[-/]\\d{1,2}[-/]\\d{1,2})|(20\\d{2}年\\d{1,2}月\\d{1,2}日)", Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
            //Matcher matcher = p.matcher(dateStr);
            Matcher matcher_detail = p_detail.matcher(dateStr);
             
            if(!(matcher_detail.find(0) && matcher_detail.groupCount() >= 1)) 
            {
                matcher_detail = p.matcher(dateStr);
                containsHMS  = true;
            }else
                matcher_detail = p_detail.matcher(dateStr);
            if (matcher_detail.find() && matcher_detail.groupCount() >= 1) { 
                matches = new ArrayList(); 
                for (int i = 1; i <= matcher_detail.groupCount(); i++) { 
                    String temp = matcher_detail.group(i); 
                    matches.add(temp); 
                } 
            } else { 
                matches = Collections.EMPTY_LIST; 
            }            
 
            if (matches.size() > 0) { 
                for(int i=0;i<matches.size();i++)
                {
                    String pubTime = matches.get(i).toString().trim();
                    //取出第一个值
                    pubTime = pubTime.replace("/", "-").replace("年", "-").replace("月", "-").replace("日", "-");
                    if(current.compareTo(TimeUtil.strToCalendar(pubTime, "yyyy-MM-dd"))>=0)
                    {
                        if(containsHMS)
                            pubTime+=" "+"00:00:00";
                        if(pubTime.matches(rightTimeReg))
                        {
                            return pubTime; 
                        }
                    }
                }
            } else { 
                return null; 
            } 
             
        } catch (Exception e) { 
            return null; 
        } 
        return null;
    }
}


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Why is Java a popular choice for developing cross-platform desktop applications?Why is Java a popular choice for developing cross-platform desktop applications?Apr 25, 2025 am 12:23 AM

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Discuss situations where writing platform-specific code in Java might be necessary.Discuss situations where writing platform-specific code in Java might be necessary.Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

What are the future trends in Java development that relate to platform independence?What are the future trends in Java development that relate to platform independence?Apr 25, 2025 am 12:12 AM

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages ​​such as Python and JavaScript to enhance cross-language interoperability.

How does the strong typing of Java contribute to platform independence?How does the strong typing of Java contribute to platform independence?Apr 25, 2025 am 12:11 AM

Java's strong typed system ensures platform independence through type safety, unified type conversion and polymorphism. 1) Type safety performs type checking at compile time to avoid runtime errors; 2) Unified type conversion rules are consistent across all platforms; 3) Polymorphism and interface mechanisms make the code behave consistently on different platforms.

Explain how Java Native Interface (JNI) can compromise platform independence.Explain how Java Native Interface (JNI) can compromise platform independence.Apr 25, 2025 am 12:07 AM

JNI will destroy Java's platform independence. 1) JNI requires local libraries for a specific platform, 2) local code needs to be compiled and linked on the target platform, 3) Different versions of the operating system or JVM may require different local library versions, 4) local code may introduce security vulnerabilities or cause program crashes.

Are there any emerging technologies that threaten or enhance Java's platform independence?Are there any emerging technologies that threaten or enhance Java's platform independence?Apr 24, 2025 am 12:11 AM

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages ​​for performance.

What are the different implementations of the JVM, and do they all provide the same level of platform independence?What are the different implementations of the JVM, and do they all provide the same level of platform independence?Apr 24, 2025 am 12:10 AM

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages ​​and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

How does platform independence reduce development costs and time?How does platform independence reduce development costs and time?Apr 24, 2025 am 12:08 AM

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)