Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Regex Question

Tags:

java

In Java - I need to search/validate an input string for a number or for a specific string. it must be one 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?

like image 692
Herbst Avatar asked Mar 04 '26 08:03

Herbst


2 Answers

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.

like image 128
Joey Avatar answered Mar 06 '26 21:03

Joey


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];
like image 44
David Z Avatar answered Mar 06 '26 21:03

David Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!