Reputation: 942
Ahoy everyone, I have the following regex pattern
String pattern1 = "([0-9+\\s|\\s])integer";
that I'm using on a string below. It suppose to select "integer" and a number followed by empty space before it, or just empty space if no number before it. I think I must be close, but I already spent all morning on it. Any help is much appreciated.
"BRTR val !http://www.w3.org/2001/XMLSchema# 78928458695 integer integer 33 integer"
The trouble is that it could be an emptySpace+integer or number+integer, in no particular order. The closest I came to is
"\\d+\\s*integer(.*)"
but that doesn't make it a pattern - it only works if there is a number before the "integer" and just gets the rest of the string, but I'd like to have it as a pattern.
Upvotes: 0
Views: 337
Reputation: 3863
Move ]
after the 9
:
"([0-9]+\\s|\\s)integer"
This matches with "78928458695 integer"
, " integer"
and "33 integer"
, assuming that I got what you wanted.
An example:
String s = "BRTR val !http://www.w3.org/2001/XMLSchema# 78928458695 integer integer 33 integer";
Pattern pattern = Pattern.compile("([0-9]+\\s|\\s)integer");
Matcher matcher = pattern.matcher(s);
List<String> list = new ArrayList<>();
while (matcher.find()) {
list.add('"' + matcher.group() + '"');
}
System.out.println(list); // ["78928458695 integer", " integer", "33 integer"]
Upvotes: 2
Reputation: 280
Given that either way you are checking for a space before the integer, you could remove that from the parentheses.
And now you're just looking for an optional integer, followed by a space, followed by 'integer', so you're final regex can be this:
"[0-9]*\\sinteger"
This matches 0 or more digits followed by a space, followed by the word integer.
Upvotes: 0