Я хочу проверить, соответствует ли строка формату - PullRequest
0 голосов
/ 15 апреля 2020

Я хочу проверить, соответствует ли string следующему формату:

"text|text|text"

В String не должно быть whitespace, только 2 числа перед da sh и 2 цифры после da sh.

Какой лучший способ сделать это?

Ответы [ 2 ]

1 голос
/ 15 апреля 2020

Java String имеет метод matches(String regex), который можно вызывать для запуска регулярного выражения в строке и возвращает логическое значение.

String regex = "^[a-zA-Z0-9]+\|[a-zA-Z0-9]+\|[a-zA-Z0-9]+$"
String myString = "text|text|text";

myString.matches(regex); // true
"test".matches(regex); // false

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

0 голосов
/ 15 апреля 2020

Возможно, это не то, что вы ищете, но мне не хватило места, чтобы оставить это как комментарий. Если вы просто хотите убедиться, что нет пробелов и есть только два '|' символы, использующие методы substring () и indexOf () из класса String. * substring (int begin, int end) - возвращает урезанную версию строки символов, проиндексированных между begin и (end - 1)

public boolean matchesFormat(String s) { if (s.indexOf(" ") == -1) { // First we use the String class's indexOf method to make sure we have no spaces anywhere in the string if (s.indexOf("|") != -1) { // Now we check to make sure we have at least one '|' symbol String cut = s.substring(s.indexOf("|") + 1, s.length()); // indexOf() only returns the index of the first appearance of the | symbol. We'll have to cut the string to remove the first and check for the second if (cut.indexOf("|") != -1) { cut = cut.substring(cut.indexOf("|") + 1, cut.length()); if (cut.indexOf("|") == -1) { // here we make sure we have two and only two | symbols return true; // because now we have determined that this string meets the criteria }<br> } } return false; because the previous algorithm was unable to prove this string to follow the criteria }</p> <p>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...