如何从句子中所有数字都是字母的单词中获取每个单词的第一个字符?

4
我有一些由单词和数字构成的句子。我想要得到一个字符串,其中包含每个单词的第一个字符、所有数字和所有大写字母的单词。我尝试使用正则表达式,但问题是它不能匹配所有数字和所有大写字母的单词。
我的正则表达式在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);
        }
    }
}

样例输入

自由式钢材

自由式合金

越野钢材英国

单速

5速

15速

内部3速带55后轮制动器

山地自行车钢材

少年山地自行车

样例输出

Fs

FA

Tsu

Ss

5s

15s

3Sigw55c

MTBs

JMTB


1
使用 var regex = @"\d+|\b\w";,然后 output += item.Value.ToUpper(); - Wiktor Stribiżew
@WiktorStribiżew:考虑到原帖的输出,他也想保留小写字母。 - Jan
@WiktorStribiżew,它可以提取所有数字,但无法提取所有大写字母的单词。 - csharpbd
1
你可以使用\d+|\b([A-Z]+|\w) - Jan
1
谢谢大家的帮助。 - csharpbd
显示剩余6条评论
3个回答

1
您可以使用的正则表达式是:
@"[0-9]+|\b(?:\p{Lu}+\b|\w)"

详情:

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

参见此解决方案:

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

1

1
你可以通过替换来实现:

string input = "3 Speed internal gear with 55 coaster";
string pattern = @"\B[a-z]+|\W+";
string replacement = "";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

\B (非单词边界) 断言匹配的字母由单词字符前导,\W 匹配任何非单词字符。

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接