简体   繁体   中英

Regex that matches lines with a leading or trailing asterisk

I need to match every line that starts or ends with a single asterisk character without any other asterisk in between.

1.- foo BAR, FOO1*

2.- *FOO, bar% foo

3- *foo). BAR", fOo*

4.- **foo BAR foo

5.- *foo bar foo**

6.- foo bar * foo

7.- foo bar foo

I want to match the lines number 1 to 3, the other lines I won't match them.

My aproach:

^[\*](?:[a-zA-Z0-9.!#$%&'+/=?^_`{|}~-\s])|^[a-zA-Z0-9.!#$%&'+/=?^_`{|}~-\s]+.\*$

but doesn't work in all cases.

Why such a complication? Try:

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

See https://regex101.com/r/oOCSE5/6

Basically, you have two cases ( first case | second case ) of matches expressed in the regex above:

  1. A string starts with a asterisk ^\* , contains no asterisk [^*]* , and ends with one or zero asterisk \*?$
  2. A string doesn't contain any asterisk ^[^*]* except the last char \*$

In the case you do not need any asterisk in the middle of the string as well - use Pierre François answer.

In the case an asterisk is accepted in the middle of the string try this:

 var tests = [ "foo BAR, FOO1*", "*FOO, bar% foo", '*foo). BAR", fOo*', "**foo BAR foo", "*foo bar foo**", "foo bar * foo", "foo bar foo"]; var regex = /(^\*(?.\*)?*(?<?\*)\*?$)|(^\*.(?;\*).*(.<.\*)\*$)/; tests.forEach(t => console.log(regex.test(t)));

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