0

I want to create a regular expression, in Java, that will match the following:

*A*B

where A and B are ANY character except asterisk, and there can be any number of A characters and B characters. A(s) is/are preceded by asterisk, and B(s) is/are preceded by asterisk.

Will the following work? Seems to work when I run it, but I want to be absolutely sure.

Pattern.matches("\\A\\*([^\\*]{1,})\\*([^\\*]{1,})\\Z", someString)
2
  • 1
    Just added my answer assuming you didn't want a match on *ABC*DEF or *A_$-123*B<>+-321. Have a look at my answer please. Commented May 23, 2013 at 17:48
  • I want a match on both AAABBB and ABCDEF. I do not know what characters and how many will be between the stars, nor their pattern. I only know that the characters cannot be asterisk as I am using it to split the string (for example AAABBB, I would have two strings AAA and BBB, or ABCDEF I would have ABC and DEF Commented May 24, 2013 at 13:51

3 Answers 3

3

It will work, however you can rewrite it as this (unquoted):

\A\*([^*]+)\*([^*]+)\Z
  • there is no need to quote the star in a character class;
  • {1,} and + are the same quantifier (once or more).

Note 1: you use .matches() which automatically anchors the regex at the beginning and end; you may therefore do without \A and \Z.

Note 2: I have retained the capturing groups -- do you actually need them?

Note 3: it is unclear whether you want the same character repeated between the stars; the example above assumes not. If you want the same, then use this:

\A\*(([^*])\2*)\*(([^*])\4*)\Z
Sign up to request clarification or add additional context in comments.

4 Comments

Do you need to escape the asterisk within the square brackets as [^\*]?
No you don't. A star/asterisk is not special within a character class, as I mentioned.
This would fail to prevent a match on something like *A_$-123*B<>+-321.
Yes indeed, but the op doesn't explicitly say that the characters inbetween the stars have to be the same. If this is the case, the initial question should be edited. (edited answer to mention 2nd solution)
0

If I got it correct.. it can be as simple as

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

1 Comment

No: the dot will capture any character, including the star, and the OP wants anytiing but the star.
0

If you want a match on *AAA*BBB but not on *ABC*DEF use

^\*([a-zA-Z])\1*\*([a-zA-Z])\2*$

This won't match on this either

*A_$-123*B<>+-321

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.