0

I got a text document with a few pieces of information I want to suck out using the magic of regular expressions. I wrote a decent regex that catches the information I needed — you can look at it here.

The regex looks like this:

\w+(?!\>)(?=\-)\W+\w+|\w+\s+\w+(?!\>)(?=\s+\d+\s+)|\w+(?!\>)(?=\s+\d+\s+)

I rewrote it to use in Java — to my knowledge, you need to add an extra backslash, like so:

\\w+(?!\\>)(?=\\-)\\W+\\w+|\\w+\\s+\\w+(?!\\>)(?=\\s+\\d+\\s+)|\\w+(?!\\>)(?=\\s+\\d+\\s+)

The problem is that what it should catch (according to several regex sites) doesn't get catched when I use it in Java. Can anyone point out why this is?

EDIT: To clarify, my regex doesn't match anything in Java.

5
  • 3
    Be careful: the Java Regex engine is not the same as many other Regex engines. Could you please provide an example of what it is that you need to match, and what it is matching in Java? Commented Mar 26, 2015 at 20:14
  • There are several different flavors of regex. Have you tried it on a Java-specific website such as Regex Planet? Commented Mar 26, 2015 at 20:14
  • @InsidiarumCrassescit – I see. If you follow my link in the description you can get a sense of what I wish to catch. Commented Mar 26, 2015 at 20:20
  • @RealSkeptic – I understand. No, I did not know of that site. Will take a look at it now. Commented Mar 26, 2015 at 20:20
  • 1
    What method are you using to evaluate the regex in Java? There are some methods that match an entire string and some that do partial matching. That may be part of the problem. Commented Mar 26, 2015 at 20:45

1 Answer 1

2

If you don't rely on all the lookaheads try using the following simplified pattern:

Pattern p = Pattern.compile("\\>([^\\d]+) ");
Matcher m = p.matcher(">Sea-Cucumber 576151 1HLB");
if (m.find()) System.out.println(m.group(1));

// prints "Sea-Cucumber"
Sign up to request clarification or add additional context in comments.

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.