【问题标题】:How to skip symbols in the end of the regular expression如何跳过正则表达式末尾的符号
【发布时间】:2013-08-19 06:56:03
【问题描述】:

我有下一个正则表达式:

const string pattern        = "(\\w)</span>";
const string replace        = "$1&nbsp;</span>";
var rgx                     = new Regex(pattern);

所以,它匹配所有以 结尾并在其前面有一个符号的东西。 我想让它匹配相同的短语,除了结尾有标点符号的那个

例子:

 Mom</span>, is awesome ....

我也不希望它匹配:

Adventure is the best</span>. So now we keep on doin it ...

我试过了:

const string pattern        = "(\\w)</span>[^\\W]$";
const string pattern        = "(\\w)</span>(^\\W)$";

但它根本不起作用。

我正在寻找的结果: 如果有一个短语:

Mom</span>, Dad

作为 html 文本的一部分,我不想匹配它,因为我不想在逗号前面添加空格 -> Mom , Dad 。我希望它在被解析后留下妈妈,爸爸。

但如果我有:

Mom</span>and Dad (After parsing it comes like : Momand Dad)

我要在“and”前加一个空格,这样解析后就可以变成“爸爸妈妈”了。

我希望你现在可以了解我想要做什么!

【问题讨论】:

  • 不要使用正则表达式来解析 html..(尝试 html 敏捷包)
  • 我实际上使用的是 html 敏捷包。当我将 html 内容分配给一个字符串时,我需要对其进行一点编辑。这就是我使用正则表达式的原因。

标签: c# regex match


【解决方案1】:

试试这个:

const string pattern  = "(\\w)</span>(?![.])";

如果标点前可能有空格,你可以试试这个:

const string pattern  = "(\\w)</span>(?!\s*[.])";

【讨论】:

  • 你能告诉我这个组 (?![.]) 到底是做什么的吗?我可以添加这个: (\\w)(?!([.]|[,]|[:])) 吗?所以我可以跳过逗号和双逗号?
  • @mathinvalidnik 称为Lookahead,您可以在正则表达式中搜索Lookahead、Lookbehind 和Look-around。如果您想添加更多字符,请尝试(?![.,:])
【解决方案2】:

怎么样:

    const string pattern        = "(\\w)</span>[^,.]";

这个 [^,.] 表示任何一个不同于: , 或 . 的字符。

您可以扩展为 [^,.;:] 或您需要的任何其他内容,也许您可​​以使用 [^,.] 像 * 或 + 这样的量词来指定可能有多个标点符号。

【讨论】:

  • 去哪儿了?
  • 我的代码缩进不好,编辑器吃掉了 ,因为它是 HTML。
【解决方案3】:
    I tried something but i could not get any direct idea. Just sharing some different method.
    Have two pattern one with punctuation and another without punctuation

    Without punctuation pattern:
        const string pattern = "(\\w)</span>([^\.\,]+)$"; (u replace with space)
    Another one with punctuation pattern:
        const string pattern = "(\\w)</span>[\,\.\\w]+$"; (u replace without space)


In both pattern add the punctuations you want at end eg. ([^\:\;]+)$

【讨论】:

  • 我无法理解您的要求,请说出您想要的输出以及您现在得到的输出。例如
猜你喜欢
  • 2010-11-23
  • 2011-10-15
  • 2013-10-30
  • 2017-09-30
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多