简体   繁体   中英

capture optional surrounding characters

I'm not that savvy in regex, so I'm not sure how to achieve the following thing:

I'd like to capture any arbitary string from an input that may or may not be surrounded by the '$' character. If a '$' character is present at the beginning of the string, the '$' character at the end must be present.

Currently I have

^\w+([_.-]\w+)*$

which roughly translates to:

  1. Arbitary word characters
  2. Beginning of capture group
  3. any character of '_', '.', '-'
  4. Before an optional \\n

So valid matches would be:

test
test-5
test.1.3
test-alpha.2

Now I'd like to make this possible

$test$

But not...

$test (or test$)
^(?:(?:\w+(?:[_.-]\w+)*)|\$test\$)$

Its better to add that with | instead off modifying the original one.See demo.

https://regex101.com/r/wU7sQ0/32

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