有一些字符串,需要提取最前面的几个字符,这些字符可能是符号、汉字、字母,需提取内容都不长,最长为2个汉字、一个符号、1个数字加一个字母或3个字母。存在以下两种情况,请问如何用C#实现:
1、如果第一个不是数字,则提取第一个数字之前的所有字符串,
字符串 | 需提取内容 |
---|---|
-10 | - |
L50*5 | L |
花纹6 | 花纹 |
WSR8010 | WSR |
2、如果第一个是数字,则提取第二个数字之前的所有字符
字符串 | 需提取内容 |
---|---|
2L50*5 | 2L |
2C1006020*2 | 2C |
字符串解析而已啊 正则都不需要用
正则:^((?:\d+)|(?!\d+))[^\d]+
C#代码:
var resultString = Regex.Match(subjectString, @"^((?:\d+)|(?!\d+))[^\d]+").Value;
正则是先验的模式匹配,就你给的测试样例,我可以给出^((?:\d+)|(?!\d+))[^\d]+这样的正则
#include "stdio.h"
#include "stdbool.h"
#include "stdlib.h"
#include "string.h"
bool check_number(char data)
{
if(data >= '0' && data <= '9')
{
return true;
}
return false;
}
int main(void)
{
char * test_str = "2C1006020*2";
char result_buf[1024];
int result_index = 0;
int len = 0;
bool first_number = false;
memset(result_buf, 0, sizeof(result_buf));
len = strlen(test_str);
first_number = check_number(test_str[0]);
if(first_number)
{
for(int i = 0; i < len; i++)
{
if(check_number(test_str[i]) && i != 0)
{
break;
}else{
result_buf[result_index++] = test_str[i];
}
}
}else{
for(int i = 0; i < len; i++)
{
if(check_number(test_str[i]))
{
break;
}else{
result_buf[result_index++] = test_str[i];
}
}
}
printf("result is [ %s ] \n", result_buf);
return 0;
}
直接在后台取出第一个字符,判断是不是数字,是就用substring截取就可以了
正则: ^\D+
最好的方法是使用 正则表达式