1

I know this sounds easy but I am stuck.
I want to match strings that has asterisk *.

Essentially I want to allow strings having asterisk at front/back/both but not middle:
(At max there will be 2 asterisks, front and both but no middle, and the presence string is a must)

ALLOW:

*string*
*string
string*
string

DENY:

*str*ing*
*str*ing
str*ing*
str*ing
*string**
**
*

I tried

^\\*?((?!\\*).)*\\\*?$

and somehow it works.
Can someone explains how this works?
And verify if this is correct because regex..hard to debug and check..

Allan
  • 11,170
  • 3
  • 22
  • 43
Salam.MSaif
  • 189
  • 10

2 Answers2

2

You can use the following regex:

^\*?\w+\*?$

demo: https://regex101.com/r/vwuXv2/1/

Explanations:

  • ^ anchor imposing the start of a line
  • \*? a * appearing at most one time
  • \w+ at least 1 word char appearing in the text ([a-zA-Z0-9_] feel free to change it depending on your need)
  • \*? a * appearing at most one time
  • $ end of line anchor

Now if you are interested in partial line matches, you can use the following regex:

(?<=^| )\*?\w+\*?(?=$| )

demo: https://regex101.com/r/vwuXv2/2/

Explanations: you add lookbehind, lookahead assertions.

Adding Japanese characters as requested in the comment (add in [^*\s] all the characters you need to exclude from the words):

^\*?[^*\s]+\*?$

demo: https://regex101.com/r/RaCmwt/1/

or

^\*?[[:alpha:]]+\*?$ 

(with unicode flag enabled) or just

^\*?\p{L}+\*?$

demo: https://regex101.com/r/RaCmwt/2/

Allan
  • 11,170
  • 3
  • 22
  • 43
  • 1
    The upper one seems like it make sense. What if the \w+ part is a japanese character? – Salam.MSaif Mar 11 '19 at 02:23
  • @Salam.MSaif: I have edited my comment to add Japanese characters, other non ascii characters. Let me know if this works for you. – Allan Mar 11 '19 at 02:39
2

You can simply say: Optionally start with asterisk, 0 or more arbitrary characters except asterisk, optionally end with asterisk.

^\*?[^*]*\*?$

https://regex101.com/r/bibCEc/2

An alternative is to inverse the match and test if there is not ( i.e. if(!...)) any asterisk not at the begin or end using negative look behind and look ahead:

(?<!^)\*(?!$)

https://regex101.com/r/8St0M4/2


According to your recent edit you would use the quatifier + to match 1 or more characters:

^\*?[^*]+\*?$

https://regex101.com/r/bibCEc/3

Quasimodo's clone
  • 5,511
  • 2
  • 18
  • 36
  • watch out `**` will be accepted by your regex! As well as `*\n*`! – Allan Mar 11 '19 at 01:57
  • @Allan That's actually intended according to the qunatifier in the example of the question. I had `+` before in the first version https://regex101.com/r/bibCEc/1 There's no example that `**` should be denied. – Quasimodo's clone Mar 11 '19 at 02:00