【问题标题】:Regular expression to check if a word is within a string including delimiters正则表达式检查单词是否在包含分隔符的字符串中
【发布时间】:2022-07-01 00:59:59
【问题描述】:

我正在尝试编写一个与包含特定单词(专业实体或公司)的字符串匹配的正则表达式。我得到的最接近的是以下内容:

(?i)(?u)(?<!\S)(((Inc)\.)|(Professional\sEntity))(?!\S)

但是,如果有特殊字符,例如,-等,则失败

应该工作的示例字符串:

test PROFESSIONAL ENTITY new
test inc. new
test inc., new
test inc.,new
inc., new test
PROFESSIONAL ENTITY new
PROFESSIONAL ENTITY new test
PROFESSIONAL ENTITY, new
PROFESSIONAL ENTITY,new
test PROFESSIONAL ENTITY,
PROFESSIONAL ENTITY,
PROFESSIONAL ENTITY, new test
PROFESSIONAL ENTITY,new test
PROFESSIONAL ENTITY-new test
PROFESSIONAL ENTITY- new test

不应工作的示例字符串:

PROFESSIONAL ENTITYnew test
test inc.test
test PROFESSIONAL ENTITYnew
testPROFESSIONAL ENTITY new

【问题讨论】:

    标签: java regex


    【解决方案1】:

    例如,您可以使用单词边界结束实体,并在inc. 之后断言不是单词字符:

    (?iu)\b(((Inc)\.(?!\w))|(Professional\sEntity\b))
    

    Regex demo

    如果您不需要捕获组:

    (?iu)\b(?:Inc\.(?!\w)|Professional\sEntity\b)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-15
      • 2017-05-03
      相关资源
      最近更新 更多