Home > Web Front-end > JS Tutorial > body text

How to use lookaround in regular expressions

php中世界最好的语言
Release: 2018-03-29 16:06:14
Original
1479 people have browsed it

这次给大家带来在正则中怎么使用环视,在正则中使用环视的注意事项有哪些,下面就是实战案例,一起来看一下。

本文实例讲述了正则表达式中环视的简单应用。分享给大家供大家参考,具体如下:

由于开发工作需要对文本中内容进行过滤,删除或替换掉一些无用的或不符合要求的信息。于是发现一个问题,某一类工程性文本中,用到很多英文写法相同、但含义不同的单位,需要将其分别转为真实含义对应的汉字。比如:"粘度为17s,移动距离为350厘米,要求混凝土必须内实外光。振捣时间为30s。",很明显第一个s是粘度的单位,第二s是时间单位,现在需要将文本中所有表示时间的s替换为“秒”,在朋友指引下,发现通过正则表达式中的环视可以方便实现这功能。

正则表达式中的环视,大家公认的基本原理是依据位置信息来进行匹配。我认为,还可以把它理解为依据目标字符的上下文进行匹配。

具体的Java代码如下

package ccnu;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class regex {
  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    String tempHtmlString="粘度为17s,移动距离为350厘米,要求混凝土必须内实外光。振捣时间为30s。";
    Pattern p_html;
    Matcher m_html;
    String regEx = "([^粘度][u4e00-u9fa5]{1,10}(?<=[0-9]))s([^a-z]$)";
    p_html = Pattern.compile(regEx);
    m_html = p_html.matcher(tempHtmlString);
    String resultString="";
    try {
      resultString = m_html.replaceAll("$1秒");
    } catch (PatternSyntaxException ex) {
      // Syntax error in the regular expression
    } catch (IllegalArgumentException ex) {
      // Syntax error in the replacement text (unescaped $ signs?)
    } catch (IndexOutOfBoundsException ex) {
      // Non-existent backreference used the replacement text
    }
    System.out.println(resultString);
  }
}
Copy after login

结果:粘度为17s,移动距离为350厘米,要求混凝土必须内实外光。振捣时间为30秒。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

匹配用户输入的银行卡号的Luhn算法

正则表达式验证qq号码是否输入正确

The above is the detailed content of How to use lookaround in regular expressions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!