gpt4 book ai didi

c# - 如何从句子中所有数字的每个单词中获取第一个字符?

转载 作者:太空狗 更新时间:2023-10-30 01:30:44 26 4
gpt4 key购买 nike

我有一些句子,它们由单词数字构成。我想从每个 word 中获取一个包含 1st charstringall digit 并且这个词有 所有大写字母。我试过使用 Regex 但问题是,它没有给出 all digitall upper case letters.

我的正则表达式在 Regex101 中.

我的解决方案是 DotNetFiddle .

代码:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Program
{
public static void Main()
{
List<string> list = new List<string> {"Freestyle steel","Freestyle Alloy","Trekking steel uk","Single speed","5 speed","15 speed","3 Speed internal gear with 55 coaster","MTB steel","Junior MTB"};
foreach(string data in list)
{
string regex = @"(\b\w)|(\d+)";
var matches = Regex.Matches(data, regex, RegexOptions.Multiline);
string output = "";
foreach(Match item in matches)
{
output += item.Groups[1];
}
Console.WriteLine(output);
}
}
}

Sample Input

Freestyle steel

Freestyle Alloy

Trekking steel uk

Single speed

5 speed

15 speed

3 Speed internal gear with 55 coaster

MTB steel

Junior MTB

Sample Output

Fs

FA

Tsu

Ss

5s

15s

3Sigw55c

MTBs

JMTB

最佳答案

您可以使用的正则表达式是

@"[0-9]+|\b(?:\p{Lu}+\b|\w)"

详细信息:

  • [0-9]+ - 一个或多个数字
  • | - 或者
  • \b - 前导词边界
  • (?:\p{Lu}+\b|\w) - 1+ 个大写字母后跟一个尾随单词边界 (\p{Lu}+\b) 或任何字符字符 (\w)。

参见 this solution :

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

public class Test
{
public static void Main()
{
var regex = @"[0-9]+|\b(?:\p{Lu}+\b|\w)";
var list = new List<string> {"Freestyle steel","Freestyle Alloy","Trekking steel uk","Single speed","5 speed","15 speed","3 Speed internal gear with 55 coaster","MTB steel","Junior MTB"};
foreach(var data in list)
{
var matches = Regex.Matches(data, regex).Cast<Match>().Select(m => m.Value.ToUpper());
Console.WriteLine(string.Join("", matches));
}
}
}

输出:

FS
FA
TSU
SS
5S
15S
3SIGW55C
MTBS
JMTB

关于c# - 如何从句子中所有数字的每个单词中获取第一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43563633/

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