0
line.matches("[A-Z] ([a-zA-z][a-zA-Z]*)|\\#")

I need to read elements like "A ddg", "B gH" or "D #"

But it doesn't work and I need to know if the regular expression is ok.

3
  • Your explanation is not clear. Which phrases are you trying to "catch" exactly? That can help understand what you are trying to achieve. Be more specific. Commented Jan 10, 2015 at 21:38
  • What do you mean by "I need to read elements like..."? Do you want to find them in your line, or do you want to check if entire line is element which can be matched by this regex? Commented Jan 10, 2015 at 21:42
  • I want to check if entire line is element which can be matched by this regex Commented Jan 10, 2015 at 21:46

3 Answers 3

2

Try this:

line.matches("[A-Z] ([a-zA-Z]+|#)")

Much of your regex is redundant:

  • \\# is the same as # - there's nothing special about #
  • [a-zA-Z][a-zA-Z]* is identical to [a-zA-Z]+

The thing you were missing was the correct alternation - you didn't have the closing bracket in the right place.

Sign up to request clarification or add additional context in comments.

Comments

1

You have this problems:

  • you closed your parenthesis too early, which placed # outside of it,
  • you used A-z range instead of A-Z.

Also you can improve your regex a little:

  • you don't need to escape #
  • instead of xx* you can use x+ since:
    • + represents once or more
    • * represents zero or more

So try with

line.matches("[A-Z] ([a-zA-Z]+|#)")

Comments

1

This will work:

line.matches("[A-Z]( [a-zA-z]+)?( #)?")

What will match (examples):

A
A #
A a
A aAaA
A a #
A aAaAa #

If you don't want "A #":

line.matches("[A-Z]( [a-zA-z]+| #)")

4 Comments

The left side(before space) is uppercase(just one character) and the right side is uppercase or/and lowercase or just #(it can be "A aa" or "B #" but no "A aa#")
Yes, that's correct. Not really sure what you wanted. Edit the question with examples if you think my solution is wrong.
FYI the leading/trailing ^ and $ are redundant. See javadoc of matches() for why
ah okay, just wanted to be sure. removed.

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.