简体   繁体   中英

Regex VB.net Should I Group?

I have wrote the following code to cut down the information I have in each line

s = Regex.Replace(s, "(a\/users\/\d*).*\(.*", "$1")

The string starts as this:

/a/users/15/badges?params%5Bnotifications%5D%5Bcount%5D=5 HTTP/1.1" 200 143 "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"

Im trying to get to

/a/users/15/ (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"

Am I going far wrong? If anyone can assist I would be grateful.


When i try this:

s = Regex.Replace(s, "(a/users/\\d*). (\\Blackberry. ).*", "$1 $2")'

To sort the following line

/a/users/80021/messages.json?params[page]=1&params[per_page]=10&params[set_actions]=true HTTP/1.1" 200 13063 "BlackBerry9320/7.1.0.398 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/603 tibbr/3.6.6.1" 1/1574070

It does not work it doesnt seem to recognise the / after the /a/users/80021

Thanks again for your help, im learning so much its great.

i will have aa look at HttpUtility as well

You shouldn't escape the slashes and match the third group as well:

(a/users/\d*/).\((.*)\).*

You also need to end the regex with .* to make sure the remaining characters are removed.

Or:

s = Regex.Replace(s, "(a/users/\d*/).*(\(.*\)).*", "$1 $2")

DEMO .

But as @Cory argues: one better uses library implemented algoritms like HttpUtility since these are designed following all specifications and less likely to contain bugs.

EDIT : About your second regex, there is an error in:

s = Regex.Replace(s, "(a\/users\/\d*).*(\Blackberry\.*).*","$1 $2")

You don't escape the brackets, but B and . , the correct regex is probably:

s = Regex.Replace(s, "(a\/users\/\d*/).*(Blackberry.*).*","$1 $2")

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.

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