How to match all first digits before # in this line
26909578#Sbrntrl_7x06-lilla.avi#356028416#2012-10-24 09:06#0#http://bitshare.com/files/dvk9o1oz/Sbrntrl_7x06-lilla.avi.html#[URL=http://bitshare.com/files/dvk9o1oz/Sbrntrl_7x06-lilla.avi.html]http://bitshare.com/files/dvk9o1oz/Sbrntrl_7x06-lilla.avi.html[/URL]#<a href="http://bitshare.com/files/dvk9o1oz/Sbrntrl_7x06-lilla.avi.html">http://bitshare.com/files/dvk9o1oz/Sbrntrl_7x06-lilla.avi.html</a>#http://bitshare.com/?f=dvk9o1oz#http://bitshare.com/delete/dvk9o1oz/4511e6f3612961f961a761adcb7e40a0/Sbrntrl_7x06-lilla.avi.html
Im trying to get this number 26909578 My try
string text = @"26909578#Sbrntrl_7x06-lilla.avi#356028416#2012-10-24 09:06#0#http://bitshare.com/files/dvk9o1oz/Sbrntrl_7x06-lilla.avi.html#[URL=http://bitshare.com/files/dvk9o1oz/Sbrntrl_7x06-lilla.avi.html]http://bitshare.com/files/dvk9o1oz/Sbrntrl_7x06-lilla.avi.html[/URL]#<a href=""http://bitshare.com/files/dvk9o1oz/Sbrntrl_7x06-lilla.avi.html"">http://bitshare.com/files/dvk9o1oz/Sbrntrl_7x06-lilla.avi.html</a>#http://bitshare.com/?f=dvk9o1oz#http://bitshare.com/delete/dvk9o1oz/4511e6f3612961f961a761adcb7e40a0/Sbrntrl_7x06-lilla.avi.html";
MatchCollection m1 = Regex.Matches(text, @"(.+?)#", RegexOptions.Singleline);
but then its outputs all text
Make it explicit that it has to start at the beginning of the string:
@"^(.+?)#"
Alternatively, if you know that this will always be a number, restrict the possible characters to digits:
@"^\d+"
Alternatively use the function Match
instead of Matches
. Matches
explicitly says, "give me all the matches", while Match
will only return the first one.
Or, in a trivial case like this, you might also consider a non-RegEx approach. The IndexOf()
method will locate the '#' and you could easily strip off what came before.
I even wrote a sscanf()
replacement for C#, which you can see in my article A sscanf() Replacement for .NET .
If you dont want to/dont like to use regex, use a string builder and just loop until you hit the #.
so like this
StringBuilder sb = new StringBuilder();
string yourdata = "yourdata";
int i = 0;
while(yourdata[i]!='#')
{
sb.Append(yourdata[i]);
i++;
}
//when you get to that # your stringbuilder will have the number you want in it so return it with .toString();
string answer = sb.toString();
The entire string (except the final url) is composed of segments that can be matched by (.+?)#
, so you will get several matches. Retrieve only the first match from the collection returned by matching .+?(?=#)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.