Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression match lines starting with a certain character OR whitespace and then that character

Tags:

regex

I am trying to write a regular expression that matches lines beginning with a hyphen (-) OR that begins with spaces or tabs and then has a hyphen. So it should match the following:

- hello!             - hello! 

Here's what I've got so far: ^(\-). But that doesn't match the second example above because it requires the first character to be a hyphen.

like image 402
maxedison Avatar asked Oct 09 '13 14:10

maxedison


People also ask

How do I match a specific character in regex?

Match any specific character in a setUse square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

How do you search for a regex pattern at the beginning of a string?

The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.

How do I specify start and end in regex?

To match the start or the end of a line, we use the following anchors: Caret (^) matches the position before the first character in the string. Dollar ($) matches the position right after the last character in the string.

When using regular expressions which of the following characters match the beginning of a line?

Start of String or Line: ^ By default, the ^ anchor specifies that the following pattern must begin at the first character position of the string. If you use ^ with the RegexOptions. Multiline option (see Regular Expression Options), the match must occur at the beginning of each line.


2 Answers

You can try

^\s*- 
  • ^: start of string
  • \s*: zero or more whitespace characters
  • -: a literal - (you don't need to escape this outside a character class)
like image 117
arshajii Avatar answered Nov 07 '22 04:11

arshajii


You can use this regex by making 0 or more spaces optional match at beginning:

^\s*- 
like image 37
anubhava Avatar answered Nov 07 '22 05:11

anubhava