java Regex Question
In Java - I need to search/validate an input string for a number or for a specific string. it must be 开发者_如何学Goone of them. For example - If I have this input lines:
cccccccc 123 vvvvvvvvv jhdakfksah
cccccccc ABC vvvvvvnhj yroijpotpo
cccdcdcd 234 vcbvbvbvbv lkjd dfdggf
ccccbvff ABC jflkjlkjlj fgdgfg
I need to find 123, ABC, 234, ABC
to look for the number I could use regex: "\d+" but to look for either of them How can I combine them?
You can specify alternatives in a regular expression by using the |
character:
\d+|[ABC]+
In your specific example, the string you want is seemingly always the second "word" (delimited by a space), so it can be beneficial to include the space in the regular expression to look for it. Either by using a capturing group to capture the part you actually want to extract:
" (\d+|[ABC]+)"
(I used quotation marks to delimit the regex). Or by using a lookbehind assertion:
(?<= )(\d+|[ABC]+)
which will only match the desired portion, but still requires the space before it.
As at least one other answer has mentioned, it looks like you're picking out the second word in a space-delimited string, and regular expressions are more work than is necessary for that task. String.indexOf
would be enough:
String line = ...;
int start = line.indexOf(" ") + 1;
int end = line.indexOf(" ", end);
String word2 = line.substring(start, end);
or, now that I think about it
String word2 = line.split(" ")[1];
You could have something like this...
^[^ ]* ([^ ]*) .*$
Something like this: [0-9]+|[a-zA-Z]+ or maybe [0-9]+|(ABC)+; not sure what your rule for the characters is.
Try this regular expression:
^\w+\W+(\w+)
And make your expression to match the begin of a line with ^
.
Try this regular expression:
"(\d+|ABC)"
精彩评论