复制listbox1中的项目......? C# [英] Copy items in listbox1...? C#

查看:75
本文介绍了复制listbox1中的项目......? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是下面用于复制listBox1中的项目的代码,它可以工作。

如果可能的话我想编辑这段代码,这样只复制部分项目,而不是整个项目。



例如:

如果内容项目:



1姓名姓氏

仅限复制:姓名姓氏

但不可复制:1。姓名姓氏(1. - 不可复制)



注意:1。总是在一个系列中,1。不会改变。



This is the code below using to copy items in listBox1, and it works.
If possible I would like to edit this code, so that to copy only part of the item, not the whole item.

example:
if the content item:

1. Name Surname
be copied only: Name Surname
but not to be copied: 1. Name Surname (1. - not to be copied)

Note: 1. is always in a series, and 1. does not change.

private void Copy()
{
    StringBuilder sb = new StringBuilder();

    foreach (string sLine in listBox1.SelectedItems)
    {
        sb.Append(sLine + Environment.NewLine);
    }

    if (!string.IsNullOrEmpty(sb.ToString()))
    {
        Clipboard.SetText(sb.ToString(), TextDataFormat.Text);
    }
}





我尝试了什么: < br $>




What I have tried:

Clipboard.SetText( string.Concat( listBox1.SelectedItems.Cast<string>().Select( item =>
 Regex.Match( item, @"^\d+\.\s+(.+)" ).Groups[1].Value + Environment.NewLine ) ) );





但这不是解决方案...



But this is not the solution ...

推荐答案

最简单的方法是检查它是否存在,如果存在,则丢弃它:

The simplest way is to check if it exists and if so, discard it:
string addme = sLine;
Match match = Regex.Match(sLine, @"(?<=1\.\s+).*");
if (match.Success)
    {
    addme = match.Value;
    }
sb.AppendLine(addme);


也许我错了,但这是一个非常普遍的问题:我怎么能切断一部分字符串?



在你的情况下,你得到一个字符串1.姓名姓氏,需要切断前导1。像例如这个:



Maybe I'm wrong but this is a very generic question: how can I cut off a part of a string?

In your case you get a string "1. Name Surname" and need to cut off the leading "1." like e.g. this:

foreach (string sLine in listBox1.SelectedItems)
{
   //sb.Append(sLine + Environment.NewLine);
   sb.Append(sLine.Replace("1.", "") + Environment.NewLine);
}





更好地使用正则表达式 - 这也是非常好的记录,例如: Regex.Replace-Methode(String,String) [ ^ ]


Clipboard.SetText(string.Join(Environment.NewLine,
    listBox1.SelectedItems.Cast<string>()
        .Select(item=>Regex.Match(item, @"^\d+\.\s+(.+)"))
        .Where(match=>match.Success)
        .Select(match=>match.Groups[1].Value)
    ));


这篇关于复制listbox1中的项目......? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆