Delete non-alphanumeric characters only from beginning to end of line

I am trying to clear some data using exe helper (C #).

I repeat each line and I want to remove invalid characters from the beginning and end of the line, that is, remove dollar characters from $$$helloworld$$$ .

This works fine using this regex: \W

However, strings containing an invalid character in the middle should be left alone, i.e. hello$$$$world great, and my regex should not match this particular line.

So, in essence, I'm trying to figure out the syntax to match invalid characters at the beginning and end of a line, but leave the lines that contain invalid characters in their body.

Thank you for your help!

+4
source share
5 answers

This is true!

 (^[\W_]*)|([\W_]*$) 

This regex matches zero or more characters without a word at the beginning ( ^ ) or ( | ) at the end ( $ )

+6
source

The following should work:

 ^\W+|\W+$ 

^ and $ are anchors for the beginning and end of the line, respectively. | in the middle is OR, so this regular expression means "either match one or more non-word characters at the beginning of a line, or match one or more non-word characters at the end of a line."

0
source

Use ^ to match the beginning of a line and $ to match the end of a line. C # Regex Cheat Sheet

0
source

Try it,

  (^[^\w]*)|([^\w]*$) 
0
source

Use ^ to match "start of line" and $ to match "end of line", i.e. code must match and delete ^ \ W * and \ W * $

0
source

Source: https://habr.com/ru/post/1438036/


All Articles