简体   繁体   English

我需要检查 Array1 中的 CHAR 是否包含我的 Array2 中的一些 CHAR,但我不能将 Contains 用于 CHAR... 如何解决?

[英]I need to check if CHAR from Array1 contains some CHAR from my Array2 but I cant use Contains for CHAR... How to solve it?

I need to convert one phone number (badly written) to correct format.我需要将一个电话号码(写得不好)转换为正确的格式。 Example: + 420 741-854()642.示例:+ 420 741-854()642。 to +420741854642 enter image description here至 +420741854642在此处输入图片描述

I think I'd just Regex replace all non digits with nothing;我想我只是用正则表达式替换所有非数字;

var messy = "+ 420 741-854()642";
var clean = Regex.Replace(messy, "[^+0-9]", "");

For the regex pattern [^+0-9] this means "a single character that is from, the set of: (all characters except) + or 0 to 9 so in practice this pattern matches the space对于正则表达式模式[^+0-9] ,这意味着“来自以下集合的单个字符:(所有字符除外) +09 ,因此实际上该模式匹配空格 , hyphen - , parentheses () etc.. And any matched character (ie a bad character) is replaced with nothing , 连字符- , 括号()等。并且任何匹配的字符(即坏字符)都被替换为空

This is a job for RegEx (Regular Expressions):) you could have something like this: /+?\d+/gm which will return three matches from +420741-854()642 as ['+420741', '854', '642'] which can of course then be concatenated.这是 RegEx(正则表达式)的工作:) 你可以有这样的东西: /+?\d+/gm 它将从 +420741-854()642 返回三个匹配项为 ['+420741', '854', '642'] 当然可以连接起来。 You could always as well replace the '+' with '00' beforehand and just concatenate matches from /\d+/gm.您也可以事先将 '+' 替换为 '00',然后连接 /\d+/gm 中的匹配项。 This just matches all digits in the string.这仅匹配字符串中的所有数字。

https://regex101.com/ is a great resource for learning RegEx. https://regex101.com/是学习 RegEx 的绝佳资源。

Technically, you can filter out digits ( c >= '0' && c <= '9' ) with a help of Linq :从技术上讲,您可以在 Z7FB58B61118DFE3058E05B8C65084CA2 的帮助下过滤掉数字c c >= '0' && c <= '9'

using System.Linq;

...

string source = "+ 420 741-854()642.";

string result = "+" + string.Concat(source.Where(c => c >= '0' && c <= '9'));

If you want to do it in the style you showed in the image then you can fix it by doing this:如果您想以图像中显示的样式执行此操作,则可以通过执行以下操作来修复它:

        string number = "+ 420 741-854()642.";
        char[] povolene = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+' };

        for(int i = 0; i < number.Length; i++) {
            if (povolene.Contains(number[i])) {

                .
                .
                .
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM