Sreetam Das
Sreetam Das

Reputation: 3389

Regex for - or _ at beginning or end of string

I've been trying to check if my string has an underscore or hyphen at either the beginning or the end.

// pass
sdq
lorem ipsum
abc_def
harry-_potter


// catch
fg_
_asq
_dqw-
-asq-sq

Tried out the following but I'm learning regex so I'm not quite sure how to go forward from here:

/^[-_]?.*[-_]$/

^        => beginning anchor
[-_]?    => start with either - or _, optionally
.*       => match any number of any character (I believe I could have used ranges here)
[-_]$    => check for - or _ at the end

I also know that one possible solution could be to use |, which is used for conditions, and what I need is to be able to check that:

There is either a hypher or underscore at the beginning or end of the string.

How can I check this? Can I use something other than |?

Upvotes: 1

Views: 2466

Answers (3)

Code Maniac
Code Maniac

Reputation: 37755

Can I use something other than |?

Just in case you don't want to use regex, use startsWith and endsWith

let arr = ['sdq', 'lorem ipsum', 'abc_def', 'harry-_potter', 'fg_', '_asq', '_dqw-', '-asq-sq']

let tester = (str) => {
  return !(str.startsWith('-') || str.startsWith('_') || str.endsWith('-') || str.endsWith('_'))
}

arr.forEach(str => console.log(str, '--->', tester(str)))

Upvotes: 0

anubhava
anubhava

Reputation: 785196

Since OP has specifically asked this part:

Can I use something other than |?

Here is a regex solution that doesn't use alternation and uses negative lookahead to apply a condition that last character must not be _ or -:

/^(?!.*[-_]$)[^-_].*/mg

RegEx Details:

  • (?!.*[-_]$) is a negative lookahead that means fail the match is - or _ are found just before end of line.
  • [^-_] is a negated character class that means match any character that is not - or _.

RegEx Demo

Having said that most simple and efficient solution would be what I wrote in my comment earlier i.e. using alternation:

/^[-_]|[-_]$/mg

Use this regex to check and fail your mismatches.

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370779

You'll need to alternate. Either match [-_] at the beginning (followed by other characters), or match any number of characters and then match [-_] at the end of the string:

^(?:[-_].*|.*[-_])$

https://regex101.com/r/e7ESHW/1

The group isn't necessary, but I think it makes the intent of the pattern clearer (a match must match the full length of the string). You can leave it out if you want:

^[-_].*|.*[-_]$

If you don't care at all about what characters get matched, and only want to see if the string starts with / ends with a dash or underscore, then you can leave out the .*s.

Upvotes: 0

Related Questions