1

I'm trying to create a regular expression that will match any given string (text or whitespace) inside of arbitrary, optional whitespace. The string itself could have whitespace in it;

I'm just trying to cut white space of the beginning and end, if it exists.

Example strings:

  1. one
  2. t
  3. three
  4. four
  5. five

Expected output:

  1. one
  2. t
  3. three
  4. four
  5. five

I've been testing on regextester.com but have so far haven't been able to get it quite right.

[^\s][\w\W]*[^\s] will match cases 1, 3, 4, and 5, but it fails for single-character strings.

[^\s]*[\w\W]*[^\s] gets 1, 2, and 4, but it includes the leading whitespace from 3 and 5.

Is there a regular expression can handle this task? I'd also settle for using option 2 above and then trimming off the leading whitespace afterwards, but not sure how to do that.

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
cjl750
  • 4,380
  • 3
  • 15
  • 27

2 Answers2

0

You don't need regex to strip whitespace. In python just use the .strip method of any text object. I am sure other languages have an equally convenient tool.

Tammo Heeren
  • 1,966
  • 3
  • 15
  • 20
0

In java you can use the .trim() method on any String. This will remove leading and trailing whitespace

" spaces at front and end. ".trim() -> "spaces at front and end"

user3206236
  • 315
  • 5
  • 14