Reputation: 73
I want to spilt Alphanumeric with two part Alpha and numeric with special character like -
string mystring = "1- Any Thing"
I want to store like:
numberPart = 1
alphaPart = Any Thing
For this i am using Regex
Regex re = new Regex(@"([a-zA-Z]+)(\d+)");
Match result = re.Match("1- Any Thing");
string alphaPart = result.Groups[1].Value;
string numberPart = result.Groups[2].Value;
If there is no space in between string its working fine but space and symbol both alphaPart and numberPart showing null
where i am doing wrong Might be Regex expression is wrong for this type of filter please suggest me on same
Upvotes: 1
Views: 488
Reputation: 2123
Try this:
(\d+)(?:[^\w]+)?([a-zA-Z\s]+)
Explanation:
(\d+)
- capture one or more digit[^\w]+
match anything except alphabets?
this tell that anything between word and number can appear or not(when not space is between them)[a-zA-Z\s]+
match alphabets(even if between them have spaces)Upvotes: 5
Reputation: 18611
Start of string is matched with ^
.
Digits are matched with \d+
.
Any non-alphanumeric characters are matched with [\W_]
or \W
.
Anything is matched with .*
.
Use
(?s)^(\d+)\W*(.*)
See proof
(?s)
makes .
match linebreaks. So, it literally matches everything.
Upvotes: 1