2

I am trying to create a regex pattern to match abcdef, abc def, etc.

The patterns I tried are:

[a-z]{3}[\s?][a-z]{3}
[a-z]{3}[\s*][a-z]{3}
[\w]{3}[\s?][\w]{3}
\w{3}\s?\w{3}

All of these seem to work for abc def, but not for abcdef.

{EDIT}

AB CD 12 ABC/15 DEF
.*\bAB CD\b\s?(\d+)\s?\bABC\b[/](\d+)\s?\bDEF\b

i am trying to extract 12 and 15.

6
  • Seems to be working for me. regexr.com?35pkl Commented Jul 31, 2013 at 23:23
  • java-regex-tester.appspot.com i tried here .. as well through code .. Commented Jul 31, 2013 at 23:26
  • It's working there as well. Commented Jul 31, 2013 at 23:28
  • 2
    Your first 3 are wrong because they include the question mark and asterisk within the square brackets, meaning "find a single character which can be a whitespace char or a question mark" -- when inside the [character set] the ? and * do not mean "0 or 1" and "0 or more" Commented Aug 1, 2013 at 1:06
  • though it works fine in the sites, it doesn't work in the code where i try to extract data using groups, matcher and pattern java methods. Commented Aug 1, 2013 at 3:15

2 Answers 2

4

How about:

[\w]{3}\s?[\w]{3}

or any of the other combinations. Just remove the \s from the brackets or put the quantifier (i.e. * and ?) outside of the bracket for the space selector:

[\w]{3}[\s]?[\w]{3}

Your bottom one should work too.

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

1 Comment

though it works fine in the sites, it doesn't work in the code where i try to extract data using groups, matcher and pattern java methods.
1

First one is close

[a-z]{3}\s?[a-z]{3}

Take the ? Out of the square brackets

java will not be reading it correct. you will need to.escape the \s to \s

2 Comments

though it works fine in the sites, it doesn't work in the code where i try to extract data using groups, matcher and pattern java methods.
escape the back slash with another backslash

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.