简体   繁体   English

正则表达式匹配整个单词或短语

[英]Regex to Match Whole Word or Phrase

I have the following input: 我有以下输入:

Hewlett Packard LaserJet Printer Thingy

I need the following output: 我需要以下输出:

LaserJet Printer Thingy

Based on Hewlett Packard being matched. 基于Hewlett Packard被匹配。

I believe this is a perfect candidate for Regex (I may be wrong) which, unfortunately, I have limited experience of, but a series of string splitting and joining seems verbose. 我相信这是Regex的理想选择(很可能我错了),不幸的是,我的经验有限,但是一系列字符串拆分和连接似乎很冗长。

What I've Tried 我尝试过的

return Regex.Replace(FullProductName, "\b" + ManufacturerName + "\b", string.Empty, RegexOptions.IgnoreCase);

I found out this doesn't work because of \\b referring to word boundaries, but here I have a phrase. 我发现这是行不通的,因为\\b指的是单词边界,但是这里有一个短语。

NOTE: It may sometimes be Sony or other one-word manufacturer names. 注意:有时可能是Sony或其他一词制造商名称。

You could use the below regex to match the manufacturer name Hewlett Packard or any other single word manufacturer names at the start. 您可以使用下面的正则表达式在开头匹配制造商名称Hewlett Packard或任何其他单个词制造商名称。 Replacing the matched strings with an empty string will give you the desired output. 用空字符串替换匹配的字符串将为您提供所需的输出。

Regex: 正则表达式:

^(Hewlett Packard\s*|[A-Z][a-z]+\s*)

Replacement string: 替换字符串:

Empty string

DEMO 演示

Code: 码:

string str = @"Hewlett Packard LaserJet Printer Thingy
Sony LaserJet Printer Thingy";
string result = Regex.Replace(str, @"(?m)^(Hewlett Packard\s*|[A-Z][a-z]+\s*)", "");
Console.WriteLine(result);
Console.ReadLine();

IDEONE 爱迪生

I don't think you need a Regex. 我认为您不需要正则表达式。 Just StartsWith and Remove is enough. 只需StartsWithRemove就足够了。

string text = "Hewlett Packard LaserJet Printer Thingy";
string manufacturer = "Hewlett Packard";
if(text.StartsWith(manufacturer))
{
    var product =  text.Remove(0, manufacturer.Length).TrimStart();
    //TrimStart used for trimming leading spaces
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM