Create array of regex matches
(4castle's answer is better than the below if you can assume Java >= 9)
You need to create a matcher and use that to iteratively find matches.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("your regular expression here")
.matcher(yourStringHere);
while (m.find()) {
allMatches.add(m.group());
}
After this, allMatches
contains the matches, and you can use allMatches.toArray(new String[0])
to get an array if you really need one.
You can also use MatchResult
to write helper functions to loop over matches
since Matcher.toMatchResult()
returns a snapshot of the current group state.
For example you can write a lazy iterator to let you do
for (MatchResult match : allMatches(pattern, input)) {
// Use match, and maybe break without doing the work to find all possible matches.
}
by doing something like this:
public static Iterable<MatchResult> allMatches(
final Pattern p, final CharSequence input) {
return new Iterable<MatchResult>() {
public Iterator<MatchResult> iterator() {
return new Iterator<MatchResult>() {
// Use a matcher internally.
final Matcher matcher = p.matcher(input);
// Keep a match around that supports any interleaving of hasNext/next calls.
MatchResult pending;
public boolean hasNext() {
// Lazily fill pending, and avoid calling find() multiple times if the
// clients call hasNext() repeatedly before sampling via next().
if (pending == null && matcher.find()) {
pending = matcher.toMatchResult();
}
return pending != null;
}
public MatchResult next() {
// Fill pending if necessary (as when clients call next() without
// checking hasNext()), throw if not possible.
if (!hasNext()) { throw new NoSuchElementException(); }
// Consume pending so next call to hasNext() does a find().
MatchResult next = pending;
pending = null;
return next;
}
/** Required to satisfy the interface, but unsupported. */
public void remove() { throw new UnsupportedOperationException(); }
};
}
};
}
With this,
for (MatchResult match : allMatches(Pattern.compile("[abc]"), "abracadabra")) {
System.out.println(match.group() + " at " + match.start());
}
yields
a at 0
b at 1
a at 3
c at 4
a at 5
a at 7
b at 8
a at 10
Regex match from array of strings in JavaScript
The problem here is that a
finds two matches in aa
. You need to make sure you match all occurrences of a regex that finds either aa
or a
in this order. It means, the regex must be /aa|a/g
and not /a|aa/g
as the order of alternation matters in regex.
Here, you can use
let arr = ["a", "aa"];
let str = "I like a problem aa";
let indicesArr = [];
arr.sort((a, b) => b.length - a.length);
const regexObj = new RegExp(arr.map(x=> x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|'), "gi");
let match;
while (match = regexObj.exec(str)) {
let obj = { start: match.index, end: regexObj.lastIndex }
indicesArr.push(obj);
}
console.log(indicesArr);
Regex: How to create an array of objects from all matches in javascript?
You could use this regex
/{(\w+)}([^{]+)(?:{\/\1})?/g
And create an array using exec
like this:
let str = "{p}This is a paragraph{/p} {img}(path/to/image) {p}Another paragraph{/p}";
let regex = /{(\w+)}([^{]+)(?:{\/\1})?/g;
let match;
let matches = [];
while (match = regex.exec(str)) {
if(match[1] == "p")
matches.push({ txt: match[2] })
else
matches.push({ [match[1]]: match[2]})
}
console.log(matches)
Make array from regex
your_array = string.match( pattern )
http://www.w3schools.com/jsref/jsref_match.asp
Adding Regex matches to an array
you need to initialize the array before you can reference it or you'll get a null reference error, also you can't reference an index that doesn't exist yet or you'll get an index out of range exception.
right now your using an array with a fixed length, so if you want to add a value to it you'll have to re-declare it one index larger every time.
If you want an array of a variable length id suggest using a list, so you can just append values to it without any issues
Dim myList = New List(Of String)
For Each foo As String In bar
myList.Add(bar)
Next
Creating Array of Regular Expressions Javascript
You don't need the loop to test every word as you can put them all into one regular expression (separated by the |
character) and let the regex engine look for any of them all at once. You could do that like this:
function unacceptable(pwd){
var unforgivable = [
"password",
"12345678",
"8675309",
"[a-z]{8,}",
"qwerty",
"asdfg",
"qazwsx",
"zxcvb",
"letmein",
"trustno1",
"omnicloud",
"monkey"
];
var re = new RegExp(unforgivable.join("|"), "i");
return re.test(pwd);
}
Working demo here: http://jsfiddle.net/jfriend00/cyVbC/
P.S. You don't have to put all the words into an array. You could just predeclare the entire regex, but I thought putting them in the array like this made for more readable code that was easier to maintain.
It could also be this:
var unforgivable = /password|12345678|8675309|[a-z]{8,}|qwerty|asdfg|qazwsx|zxcvb|letmein|trustno1|omnicloud|monkey/i;
function unacceptable(pwd){
return unforgivable.test(pwd);
}
Can't get an Array of matches using Regular Expression
There are two problems:
You're not allowing for the fact your backslashes are in a string literal.
You're not passing anything into
compile
.
1. Backslashes
Remember that in a string literal, a backslash is an escape character, so the \d
in your string is an unnecessary escape of d
, which results in just d
. So your actual regular expression is:
^(d{1,2}/d{1,2}/d{1,2})
Use the literal form instead:
const reg: RegExp = /^(\d{1,2}\/\d{1,2}\/\d{1,2})/; // No `compile`, see next point
Live Example:
const stringWithDate/*: string*/ = "4/7/20 This is a date!";
const reg/*: RegExp*/ = /^(\d{1,2}\/\d{1,2}\/\d{1,2})/; // No `compile`, see next point
const exist/*: boolean*/ = reg.test(stringWithDate)
const matches/*: RegExpExecArray | null*/ = reg.exec(stringWithDate);
console.log(exist);
console.log(matches);
C# - Can you do an array of Regex search patterns?
Try this
Regex[] regexCollection = new Regex[4];
Regex intRegex = new Regex(@"((?<!\S)[A-Za-z]{2}\d{1,5}\S+\s+)|(\s[A-Za-z]{7,15}\d{1,5}\S+\s+)", RegexOptions.Compiled);
Regex psRegex = new Regex(@", id\s+\d{10},", RegexOptions.Compiled);
Regex cidRegex = new Regex(@"\d{3}-\d{3}-\d{4}", RegexOptions.Compiled);
Regex vcidRegex = new Regex(@"vcid\s\d{10},", RegexOptions.Compiled);
regexCollection[0] = intRegex;
regexCollection[1] = psRegex;
regexCollection[2] = intRegex;
regexCollection[3] = vcidRegex;
Create array of regex match(multiline)
You're pretty close - try this regex instead:
^\..*?(?=(^\.|\Z))
In java, this would be"
"^\\..*?(?=(^\\.|\\Z))" // escaping the backslashes for java String.
Splitting strings based on regex expression
# If the string matches a certain pattern, split it in two.
[array] $tokens =
if ($str -match '^(\d{3})([a-z]\d)$') { $Matches.1, $Matches.2 }
else { $str }
# Test if all tokens exist as elements in the array.
# -> $true, in this case.
$allTokensContainedInArray =
(Compare-Object $array $tokens).SideIndicator -notcontains '=>'
The regex-based
-match
operator is used to test whether$str
starts with 3 digits, followed by a letter and a single digit, and, if so, via capture groups ((...)
) and the automatic$Matches
variable, splits the string into the part with the 3 digits and the rest.The above uses
Compare-Object
to test (case-insensitively) if the array elements derived from the input string are all contained in the reference array, in any order, while allowing the reference array to contain additional elements.
If you want to limit all input strings to those matching regex pattern, before even attempting lookup in the array:
# If no pattern matches, $tokens will be $null
[array] $tokens =
if ($str -match '^(\d{3})([a-z]\d)$') { $Matches.1, $Matches.2 }
elseif ($str -match '^\d{3}$') { $str }
elseif ($str -match '^[a-z]\d$') { $str }
Related Topics
How to Get the Current Date/Time in Java
Conditionally Ignoring Tests in Junit 4
How to Deal with a Slow Securerandom Generator
What Is Suppresswarnings ("Unchecked") in Java
Places Where Javabeans Are Used
Nosuchmethoderror in Javax.Persistence.Table.Indexes()[Ljavax/Persistence/Index
How to Find the Duration of Difference Between Two Dates in Java
Differences in Boolean Operators: & VS && and | VS ||
Which Is More Efficient, a For-Each Loop, or an Iterator
How to Reference Javafx Fxml Files in Resource Folder
Left Padding a String with Zeros
Why Java Needs Serializable Interface
.Toarray(New Myclass[0]) or .Toarray(New Myclass[Mylist.Size()])
Concatenating Null Strings in Java
Multiple Wildcards on a Generic Methods Makes Java Compiler (And Me!) Very Confused
Handling Interruptedexception in Java