[英]Create regex match pattern from a string
Is there a way, using c# or vb, to take a string (in this case a phone number) and construct a regex match string from it, so that it also ignores spaces or other characters in there?有没有办法使用 c# 或 vb 来获取一个字符串(在这种情况下是电话号码)并从中构造一个正则表达式匹配字符串,以便它也忽略其中的空格或其他字符?
So a match would be found on all of these assuming the input string was 01789000111 :-因此,假设输入字符串为 01789000111 ,则会在所有这些中找到匹配项:-
01789 000111 OR 01789 000 111 OR 01789 00 01 11 OR (01789) 000111 01789 000111 或 01789 000 111 或 01789 00 01 11 或 (01789) 000111
Remove the non-digits with a regex replace then compare:使用正则表达式替换删除非数字然后比较:
var match = Regex.Replace(src, @"\D+", "") == target;
Alternatively, you could convert the target digits to a pattern and test:或者,您可以将目标数字转换为模式并进行测试:
var ans = Regex.IsMatch(src, Regex.Replace(target, @"\d", @"\D?$0\D?"))
If you are comparing a lot of src
strings to the target, you should probably create a compiled Regex
from the target:如果您将大量
src
字符串与目标进行比较,您可能应该从目标创建一个已编译的Regex
:
var tpattern = new Regex(Regex.Replace(target, @"\d", @"\D?$0\D?"), RegexOptions.Compiled);
var ans = tpattern.IsMatch(src);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.