gpt4 book ai didi

asp.net - 正则表达式 .net 风格

转载 作者:行者123 更新时间:2023-12-02 17:11:42 26 4
gpt4 key购买 nike

不要问这是如何工作的,但目前确实如此 ("^\|*(.*?)\|*$") ...有点。这删除了所有额外的管道,第一部分,我已经搜索遍了,还没有答案。我正在使用 VB2011 beta、asp web 表单、vb 编码!

我想捕获特殊字符管道(|)用于分隔单词,即 car|truck|van|cycle .

问题在于用户经常使用开头、尾随、使用多个以及在每个管道之前和之后使用空格,即 |||car||truck | van || cycle

另一个例子:george bush|micheal jordon|bill gates|steve jobs <-- 这是正确的,但是当我删除空格时,它会删除正确的空格。

所以我想去掉任何前导、尾随的空格以及 | 之前的任何空格。 | 之后的空格并且只允许一根管道(|)当然是在字母数字字符之间。

最佳答案

要求:

  • 移除所有前管或尾管
  • “修剪”内部术语周围的空格
  • 删除“一次多个管道”

这些是一些示例输入 -> 输出:

"|||car | boat|||" -> "car|boat"
"george bush|micheal jordon|bill gates|steve jobs"
-> "george bush|micheal jordon|bill gates|steve jobs"
" george bush|micheal jordon |bill gates |steve jobs "
-> "george bush|micheal jordon|bill gates|steve jobs"
"123|||123" -> "123|123"

您的示例几乎适合您:

("^\|*(.*?)\|*$")

在我们进一步讨论之前,最好先提一下这个 MSDN 引用页面:http://msdn.microsoft.com/en-us/library/az24scfc.aspx

这个在线测试页面:http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

我的正则表达式不够强大,因为我认为这个正则表达式可能有效,但看起来是一项艰巨的工作。我内联记录了,但它仍然很复杂(而且完全不起作用)

^(?:\|*)((?:\s*)([a-zA-Z0-9]?[a-zA-Z0-9 ]*[a-zA-Z0-9]?)(?:\s*)\|?(?:\|*))(?:\|*)$

^ - start the line/input
(?:\|*) - capture any pipes at the beginning but ignore them
( - begin matching so we can get the values out the other side
(?:\s*) - trim leading spaces
[a-zA-Z0-9]?[a-zA-Z0-9 ]*[a-zA-Z0-9]? - match any alphanumerics with spaces in between
(?:\s*) - trim trailing spaces
\| - match any one pipe
(?:\|*) - ignore any remaining pipes in a row
)* - end matching, we should be done
(?:\|*) - capture any pipes at the end but ignore them
$ - end of the line/input

那么,让我们尝试解决这个问题,好吗?

您应该分割管道,向前看,看看下一个是否是空长度字符串,如果不是,则将其添加到现有的单词长度中。让我们尝试一下:

(这部分我将使用 DotNetPad)http://dotnetpad.net/ViewPaste/4bpRXD-vZEOwqTLDQbEECg

这是一个示例应用程序,可以轻松满足您的需求:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class DotNetPad {
public static void Main(string[] args) {
string[] tests = new[] {
"|||car | boat|||",
"george bush|micheal jordon|bill gates|steve jobs",
" george bush|micheal jordon |bill gates |steve jobs ",
"123|||123"
};

foreach(var s in tests)
Console.WriteLine(CleanString(s));
}
public static string CleanString(string input) {
string result = string.Empty;

string[] split = input.Split(new[] {
'|'
});

foreach(var s in split) {
if (!string.IsNullOrEmpty(s)) {
result += "|" + s.Trim();
}
}
return result.Substring(1);
}
}

我最多花了 10 分钟在第二个代码上,以及自从我编辑帖子以来尝试让正则表达式工作的所有内容。这个故事的寓意是:只做你必须做的工作,你不必对所有事情都使用正则表达式。

关于asp.net - 正则表达式 .net 风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11131044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com