[C#]初学者的正则表达式问题 [英] [C#] Beginner's Regex Question

查看:79
本文介绍了[C#]初学者的正则表达式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化较大字符串的部分。



这是原始格式:



 PlayerX显示7c 8h 





...其中PlayerX是一个变化的玩家名称,最后一个两张数据的扑克牌价值也各不相同。



我希望这样格式化



 PlayerX:显示[7c 8h] 





...在玩家姓名后添加冒号卡片值周围的方括号。



这是许多尝试中的一个(显然是错误的,但是花了最后三个小时阅读有关正则表达式而没有洞察力):



 Regex rgx = new Regex(shows .. ..); 
handdata = rgx.Replace(handdata,:shows [.. ..]);





我如何导致卡值显示在重新格式化的版本中?

解决方案

请参阅我的评论。你没有真正定义一组可能的输入字符串来匹配。



只是为了给你一个想法,我会添加一些可能不是你的假设。我假设玩家名称的标准是这样的:这是从输入字符串的开头以:开头的任何字符串,因此,它可以包含除行尾和:之外的任何字符。 。另外,我假设剩余的3个单词由一个退格字符分隔。



然后匹配的字符串将是

 


(。*?\:显示)(.. ..)



我添加了( )括号定义,所以替换的例外将是

 


1

I am trying to format portions of larger strings.

Here is the original formatting:

PlayerX shows 7c 8h



...where PlayerX is a player name that varies and the last two pieces of data are playing card values which also vary.

I wish to format it like this

PlayerX: shows [7c 8h]



...adding a colon after the player name and square brackets around the card values.

Here is one of many attempts (obviously wrong, but spent the last three hours reading about regex with no insight):

Regex rgx = new Regex(" shows .. ..");
handdata = rgx.Replace(handdata, ": shows [.. ..]");



How do I cause the card values to display in the reformatted version?

解决方案

Please see my comments. You did not really define the set of possible input strings to match.

Just to give you an idea, I'll add some assumptions which might be not yours. I'll assume that the criteria for the player name is this: this is any string starting from the very beginning of the input string ending by ":", therefore, it can contain any characters except end-of-line and ":". Also, I'll assume that remaining 3 words are delimited by exactly one backspace character.

Then the matching string will be


(.*?\: shows )(.. ..)


I added () brackets to define groups, so exception to replace would be


1


这篇关于[C#]初学者的正则表达式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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