Posts by hkotsubo • 55,826 points
1,422 posts
-
3
votes1
answer613
viewsA: preg_replace_callback() to remove characters that are not digits
If you just want to remove everything that is not numbers, you can simply use preg_replace: echo preg_replace('/[^0-9]/', '', '74.208.285/0001-97'); // 74208285000197 In this case, anything that is…
-
3
votes2
answers1159
viewsA: How to use the Pattern attribute with regular expression correctly?
You can use the pattern equal to ^[1-9][0-9]{0,3}$: /* deixar borda vermelha enquanto o campo for inválido */ input:invalid { border: red 1px solid; } <form> <input type="text"…
-
3
votes2
answers169
viewsA: Remove all after the second occurrence of a comma
An alternative is: exemplo <- c("Rua Pajé, 30, apto 44", "Av. Brasil,55, blocoB") gsub("^([^,]+,[^,]+),.*$", "\\1", exemplo) I use the markers ^ and $, which are respectively the beginning and…
-
1
votes1
answer1540
viewsA: How to catch the start and end of the week on Moment.js
If you want to change the day of the week, just use the method day, passing a value between zero (Sunday) and 6 (Saturday): let agora = moment(); let inicio = moment().day(0); // domingo desta…
-
2
votes2
answers436
viewsA: Advancing Dates with Local Date
The classes of java.time sane immutable, and methods such as plusDays return another instance with the modified values. That is, if you just do: dataHoje.plusDays(1); The return of the method is…
-
2
votes1
answer76
viewsA: How to select standard words using Regex?
An alternative is to use this regex: ^- [-+]?\w+(\.\w+)*$ If the structure is rigid, better use the markers ^ and $, which are, respectively, the beginning and end of the string. So you ensure that…
-
4
votes1
answer1967
viewsA: How to take data from a JSON with Python
To learn how to read and manipulate a JSON, it becomes easier when we understand its syntax: what’s in the square brackets ([]) is an array: a list of multiple elements what’s between the keys ({})…
-
4
votes1
answer270
viewsA: Function . filter() for a List<Class>
You don’t need to create another filtered list, you can enjoy using it streams and use the method filter: Map<String, List<Pessoa>> map = listPessoas.stream() // filtrar pelo critério…
-
3
votes2
answers430
viewsA: Regex to get different snippets of a file
It would be interesting to have more details about the exact file format and a few more examples, but anyway, I’ll leave a more general solution, and you adapt according to what you need. For this…
-
2
votes2
answers60
viewsA: Unexpected outputs of a user’s serial listing code
The first problem (does not update the serial number) happens because you are not incrementing the counter i inside the loop. The second problem is solved by checking the size of the typed string,…
-
1
votes1
answer649
viewsA: How to undo merge keeping changes made after
For cases like this, I prefer to create a temporary branch, make changes to it and only at the end, I change the branch I want (in case, Feature) to point to this temporary branch. So first we have…
-
2
votes1
answer438
viewsA: How to validate a numerical expression with a regular expression?
Like you said that the expression can be "anything", I’m guessing it can have more than one pair of nested parentheses, like for example: 690.91+(1.3*(4-7/(3+6.4))) Your regex can’t detect that,…
-
3
votes2
answers213
viewsA: Find letters in the middle of the preg_grep array
About the regex you used: '/^'.$find.' (\w+)/i'. As the variable $find is "as", the end result is /^as (\w+)/i. Bars are regex delimiters and are not part of the expression itself. Then we have the…
-
5
votes1
answer63
viewsA: What is the "groups" property in the result of a Regex?
According to the documentation, the property groups contains the named capturing groups (capture groups with name): An array of named capturing groups or undefined if no named capturing groups Were…
-
2
votes2
answers194
viewsA: Remove text within a comment tag with PHP?
As already commented, one option is to use strip_tags, as it will remove the HTML comments from the string: $string = '<p>texto</p><!-- /* Font Definitions */ @font-face…
-
2
votes1
answer626
viewsA: Sort string containing letters and numbers
When you compare strings, even the digits are compared taking into account the lexicographical order of the characters (i.e., their numerical value is not taken into account, instead a comparison is…
-
6
votes1
answer148
viewsA: PHP date function is returning the day in place of the month
According to the documentation, when the string is in the formed "xx/yy/zzzz", it is interpreted as "month/day/year". One option to resolve this is to use DateTime::createFromFormat to do the…
-
3
votes3
answers227
viewsA: Add a string before a given word using Regex
Maybe regex is not the best solution for your case (for reasons that will be detailed below). Anyway, if you are only dealing with simple lines like the ones in the question, I can do this: You can…
-
1
votes2
answers5347
viewsA: Know how many years, months, days, hours, etc have passed since a certain date
One option is to install the module dateutil (pip install python-dateutil) and use a relativedelta, that calculates the difference between two datetime's the way you wish: from datetime import…
-
2
votes3
answers159
viewsA: Scanner gives error if inverting the order in which data is read
Let’s run some tests to see what happens to each reading done by Scanner, and so understand why "works" in some cases and in others not. First let’s see what happens when you read the number before…
-
3
votes3
answers826
viewsA: Calculate hours worked
You can create a function to do the Parsing of each of the time strings, and then calculate the amount of minutes between them: function parse(horario) { // divide a string em duas partes, separado…
-
1
votes1
answer228
viewsA: Regular Expression - Split disregarding anything within parentheses
The problem is to detect that the point is within parentheses, because the regex must check if there is the corresponding opening and closing, and if they are properly balanced, etc.(besides the…
-
4
votes4
answers2571
viewsA: Number of vowels in the Python function
One way to solve it is to use a comprehensilist on (much more succinct and pythonic): vogais = 'aeiou' s = 'abcdefghijABCEx' qtd_vogais = len([c for c in s.lower() if c in vogais]) print(qtd_vogais)…
-
1
votes1
answer64
viewsA: Ruby Language - Question about methods
The error in your code is: no implicit Conversion of Fixnum into String (Typeerror) I mean, you’re trying to concatenate a number (250) in a string ("velocidade do carro é de"). To resolve this, you…
-
3
votes1
answer1739
viewsA: Error using scanner.close()
This happens because, when closing the Scanner, you also close the object it encapsulates. In the case, you end up closing the System.in. Only that the System.in is a "special" resource, managed by…
-
5
votes4
answers317
viewsA: Regex to identify all occurrences of years
The problem is that findall traverse the string from left to right, and each time you find a match, the next search starts after the last found stretch. In this case, in the string 0420202198, after…
-
4
votes2
answers3919
viewsA: Check Even Numbers
As the another answer I said, all you had to do was increase the x outside the if. As it stands, your code only increases x if he is even. But then he becomes odd and is never incremented (because…
javascriptanswered hkotsubo 55,826 -
4
votes2
answers2455
viewsA: Build error: "Resource Leak" when using Scanner
Like general rule, it is important to close everything you opened, be a Scanner, an archive (FileInputStream/FileReader), a connection to a URL or a database, or whatever can be "opened" and…
-
1
votes1
answer66
viewsA: date does not show full date, only year
When you do $ano/01/01, you’re getting the value of $ano and dividing by 1 twice (i.e., the result will be the very value of $ano - in this case, 2019). This is because $ano, although it is a…
-
6
votes3
answers6345
viewsA: How to turn upper-case and lower-case letters into upper-case letters in Python?
The method you seek is swapcase. Only by complementing the other answers, the documentation mentions that not always s.swapcase().swapcase() == s. That is, if you flip the upper and lower case, and…
-
5
votes2
answers1352
viewsA: Validate field to accept integer and decimal numbers
You can use the property pattern, that defines the format the field can have, using a regular expression for that: /* deixa uma borda vermelha enquanto o campo estiver inválido */ input:invalid {…
-
4
votes2
answers454
viewsA: How to create a script to rename files on Ubuntu 18?
Just make a for in the files and use the command mv to rename them: for i in nanatsu*.mp4; do mv $i ${i#nanatsu-ep-}; done The for goes through all the files whose names correspond to nanatsu*.mp4…
-
2
votes2
answers413
viewsA: Inputmask Regex
When using {19}, you’re saying that what comes before repeats itself exactly 19 times. But from what I understand, this is as many times as it can repeat, so we missed putting the minimum size. If…
-
5
votes3
answers1314
viewsA: How to handle different date formats?
As I said before here, here and here: Dates have no format A date is just a concept, an idea: it represents a specific point in the calendar. The date of "January 1, 1970" represents this: the…
-
1
votes1
answer133
viewsA: Regex - How to recover the first occurrence of two uppercase letters after a comma in Mysql?
From Mysql 8, you can use the function REGEXP_SUBSTR, which returns only the passage corresponding to the regular expression. However, the regex ', [A-Z]{2}' will also return the comma and the…
-
3
votes2
answers662
viewsA: How to convert a date format to ISO 8601 in Javascript?
The method toISOString() returns a string containing both date and time, so an alternative would be to simply take the part that matters, using substr: let d = new Date();…
-
1
votes2
answers933
viewsA: Pick up only the final stretch after the regular expression bar
You said you’re using Google Sheets, but you didn’t say if all the text is in the same cell. In the solution below, I am assuming that each row is in a different cell (this makes the solution…
-
1
votes2
answers194
viewsA: How to recover all occurrences [[xxx]] of a string in PHP?
In the your answer (which is not wrong), you use the flag U, which causes the quantifier * not be Greedy (greedy), making it Lazy (lazy). It’s the same as wearing /\[\[(.*?)\]\]/ - use .*? without…
-
5
votes1
answer247
viewsA: Using replace in a character in the middle of a String to add text before and after the String
The t came from the word Math and the problem is in the indexes that you pass to substring (the values end up coinciding with the t). Anyway, to solve this with regex, I’m assuming some premises:…
-
4
votes3
answers347
views -
3
votes3
answers1959
viewsA: How to determine which characters can enter the input?
Your answer came close. But according to the documentation, the regular expression used in the attribute pattern must be a valid regex in Javascript. So I ran a test with your regex: let r =…
-
3
votes3
answers3895
viewsA: Python date validation (tests)
Because day, month, and year values are numerical, it is best to turn them into numbers. The comparisons you make with strings take into account the lexicographical order ("alphabetic") and "works"…
-
6
votes2
answers129
viewsA: Logic to check month with Regex
Just use the delimiters ^ and $, to mark the beginning and end of the string. So it does not take the zero of the 10 unintentionally: var mes = "10"; var teste = /^([024679]|11)$/.test(mes);…
-
1
votes1
answer35
viewsA: Remove two values from a text file
The method csv.reader returns a Reader which you should use to iterate through the lines of the file. For each line, a list containing the respective fields is returned. How you used the delimiter='…
-
1
votes1
answer196
viewsA: Qpython 3 if/Elif/Else
The function input returns a string, and we if's you are comparing with numbers. So you can choose whether to compare with strings (by placing the numbers between quotes): x = input('Select an…
-
2
votes1
answer2891
viewsA: Java 8 - Browse list, change found case, if not, add
If you’re worried about processing, maybe shouldn’t wear streams, since they have their cost and for that reason are slower than a loop traditional. Another point is that maybe you’re complicating…
-
1
votes2
answers245
viewsA: How to remove a character-specific string from a Python string
You can use the method replace, but passing '\r\n' at once (and not separately, as you did): texto = 'Let the bird of loudest lay\r\nOn the sole Arabian tree\r\nHerald sad and trumpet be,\r\nTo…
-
3
votes3
answers676
viewsA: Factor of a number chosen by the user
You can use a separate function to calculate the factorial, as already suggested in the other answers. But you can also do everything in one loop. The account starts with 1, and then adds up to 1/1!…
-
1
votes2
answers2000
viewsA: Generate and format dates with Moment in Nodejs
These times (midnight and 23:59:59) represent respectively the beginning and end of the day, so just use the functions startOf and endOf, that make the appropriate adjustments for these times,…
-
3
votes1
answer209
viewsA: Function date shows wrong value of minutes in PHP
According to the job documentation date, the letter m corresponds to the numerical value of the month (so he’s showing the value 04, because it’s April and when the second parameter is not passed,…