java - 正则表达式查找字母和数字由符号分隔或不分隔的单词

标签 java regex

我需要构建一个正则表达式来匹配具有这些模式的单词:

字母和数字:

A35, 35A, B503X, 1ABC5

以“-”、“/”、“\”分隔的字母和数字:

AB-10, 10-AB, A10-BA, BA-A10, etc...

我为它写了这个正则表达式:

\b[A-Za-z]+(?=[(?<!\-|\\|\/)\d]+)[(?<!\-|\\|\/)\w]+\b|\b[0-9]+(?=[(?<!\-|\\|\/)A-Za-z]+)[(?<!\-|\\|\/)\w]+\b

它部分起作用,但它仅匹配字母或仅匹配由符号分隔的数字。 示例:

10-10, open-office, etc.

我不想要这场比赛。

我想我的正则表达式非常重复而且有点难看。 但这就是我现在所拥有的。

谁能帮帮我?

我正在使用 java/groovy。

提前致谢。

最佳答案

有趣的挑战。这是一个带有正则表达式的 Java 程序,它可以挑选出您所追求的“单词”的类型:

import java.util.regex.*;
public class TEST {
    public static void main(String[] args) {
        String s = "A35, 35A, B503X, 1ABC5 " +
            "AB-10, 10-AB, A10-BA, BA-A10, etc... " +
            "10-10, open-office, etc.";
        Pattern regex = Pattern.compile(
            "# Match special word having one letter and one digit (min).\n" +
            "\\b                       # Match first word having\n" +
            "(?=[-/\\\\A-Za-z]*[0-9])  # at least one number and\n" +
            "(?=[-/\\\\0-9]*[A-Za-z])  # at least one letter.\n" +
            "[A-Za-z0-9]+              # Match first part of word.\n" +
            "(?:                       # Optional extra word parts\n" +
            "  [-/\\\\]                # separated by -, / or //\n" +
            "  [A-Za-z0-9]+            # Match extra word part.\n" +
            ")*                        # Zero or more extra word parts.\n" +
            "\\b                       # Start and end on a word boundary", 
            Pattern.COMMENTS);
        Matcher regexMatcher = regex.matcher(s);
        while (regexMatcher.find()) {
            System.out.print(regexMatcher.group() + ", ");
        } 
    }
}

这是正确的输出:

A35, 35A, B503X, 1ABC5, AB-10, 10-AB, A10-BA, BA-A10,

请注意,唯一“丑陋”的复杂正则表达式是那些未正确格式化和注释的正则表达式!

关于java - 正则表达式查找字母和数字由符号分隔或不分隔的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732035/

相关文章:

java - 不满意的链接器错误 : library file not found

java - 推文分析: How to design

java - 正则表达式中的 (DEFINE) 功能在 Java 中不起作用

javascript - 在 Javascript 中使用正则表达式

regex - 如何使用正则表达式查找辅音簇?

java - 从文本文件中搜索字符串(不区分大小写)

java - 我应该在 EDT 中创建的线程内调用 InvokeLater 吗?

java - Java 中的死锁(附示例)

JavaScript 正则表达式?或者其他非常正确的文本输入方法

regex - Oracle - 确定正则表达式支持的最大大小