Regex pattern with whitespace
Regex pattern with whitespace
Hello. I'm having a issue with regex patterns with whitespace inside. If I setup a regex search with the pattern ^ 123$
(notice the whitespace after the ^
), it will match 123
as expected, but also test123
. As long as my data begins with a whitespace and ends with 123
, it will match. Is this expected? I can work around this by replacing whitespaces with \\s
in my regex pattern, but I would not expect this to be necessary?
Here is my reproducible case:
<html>
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script>
const data = [
{
'id': ' test123',
},
{
'id': ' 123',
}
]
$(document).ready(function () {
$('#mytable').DataTable({
'data': data,
'columns': [
{
'title': 'ID',
'data': 'id'
}
],
'searchCols': [
{
'search': '^ 123$',
'regex': true
}
]
});
});
</script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" />
</head>
<body>
<table id="mytable">
</table>
</body>
</html>
This question has an accepted answers - jump to answer
Answers
I wouldn't call that "working around it". That's how regex works.
Since your question is not specific to Datatables I recommend to check Stackoverflow for example:
https://stackoverflow.com/questions/14718221/match-a-word-with-leading-white-space
I was curious about this one as I wouldn't actually expect
^ 123$
to matchtest123
.I suspect the issue here is that your regex and our "smart" regex and clashing. Try adding
smart: false
to yoursearchCols
object.Allan
Adding
smart: false
did the trick. Thank you, did not think about that!rf1234: Replacing whitespace with
\s
is not always desirable, as\s
also will match tab, newline and some other characters as well.Yep, I was wrong when I thought this was a pure regex question and didn't think about the "smart" setting. Good you got it sorted!